crunchy crunchy - 2 months ago 9
PHP Question

Notice: Undefined offset: 1 when creating a Array-Element?

I have a curious behavior which I can't explain. I loop a Array with

foreach
to create a other output-array from it's values:

$tabCount = 0;
$mainDivs = array();

foreach($output as $node) {
$tabCount++;
$mainDivs[$tabCount] .= 'blablabla';
}


the output is there and seems to be correct (nothing missing). But PHP throws me a Notice:


Notice: Undefined offset: 1 in E:\XAMPP\htdocs\WP\wp-content\plugins\test\php\test.php on line 163


line 163
is the line where I do the
$mainDivs[$tabCount] .= 'blablabla';


How can that be? I mean, I do create the array element(?)

Answer

. is used for concatenation not for array assignment.So remove it

So the code must be:-

$tabCount = 0;
$mainDivs = array();
if(isset($output) && count($output)>0){ // Check that your array is set and have values so that foreach will not produce error
   foreach($output as $node) {
      $mainDivs[$tabCount] = 'blablabla';
      $tabCount++; 
  }
}

Note:-

Reference:-

String concatenation:- http://php.net/manual/en/language.operators.string.php

Array:- http://php.net/manual/en/language.types.array.php