Search code examples
phparraystypesindices

PHP Array as index without array


I have a PHP Script which works quite fine except that I get this error Message

Undefined index: Array in [...]/exp.php on line 239

On this line there is this code:

$out_kostenstelle = $kostenstellen[$nextShift["kostenstelle"]][1].
    "(".$nextShift["kostenstelle"].")";

I think the only part where an Array as an Index can occur ist the part where $nextShift["kostenstelle"] is the index for $kostenstellen.

However when I try to catch this part (it is in a loop with many hundred runs so I can not manually check it) with this code, my script never enters the part inside the if clause

if(is_array($nextShift["kostenstelle"]))
{
    echo "<pre>";
    var_dump($nextShift);
    echo "</pre>";
    die();
}

This does not make any sense to me and I tried many things. without success.

I think this might be enough of the code where the error could be but just in case here are the structure of $kostenstellen and $nextShift

Kostenstellen:

array(2) {
  [100]=>
  array(2) {
    [0]=>
    string(3) "100"
    [1]=>
    string(11) "Company A"
  }
  [200]=>
  array(2) {
    [0]=>
    string(3) "300"
    [1]=>
    string(12) "Company B"
  }
}

and nextShift:

array(4) {
  ["id"]=>
  string(2) "168"
  ["start_unix"]=>
  string(10) "1466780000"
  ["end_unix"]=>
  string(10) "1466812400"
  ["kostenstelle"]=>
  string(3) "100"
}

Solution

  • There's no way around it: the problem is that the index you're trying to use is itself an array.

    When you access an array in php, $array[$index], PHP will try to stringify it if it's not already a string or numeric. Stringifying an array gives the literal "Array"; like you have here.

    However, there's another possibility: that when you run your loop, the array was stringified already. It means someplace before, someone casted it to a string.

    You could check if with such an if:

    if(is_array($nextShift["kostenstelle"]) || $nextShift["kostenstelle"] == "Array")
    {
        echo "<pre>";
        var_dump($nextShift);
        echo "</pre>";
        die();
    }