-2

I'm having an Undefined offset-Error in this PHP-Code:

$testvar1 = false;
$testvar2 = true; 

$testarray = [
            "test1" => $testvar1,
            "test2" => $testvar2
];

echo $testarray[0];

Notice: Undefined offset: 0 in /Path/to/ on line 9

So how to fix?

HelloToYou
  • 335
  • 5
  • 14
  • There is no `0` index in there. If you run `print_r($testarray);` you'll se that you only have `test1` and `test2` as keys... – FirstOne Jul 02 '16 at 16:40
  • Access it like so `$testarray['test1'];`. (A note, `var_dump($testarray['test1'])` is better to see the content in that case) – FirstOne Jul 02 '16 at 16:41
  • [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – FirstOne Jul 02 '16 at 16:42

2 Answers2

0

Please see that this is an associative array, where the array keys are "test 1" and "test 2".

If you want to print the first array element, you can write:

echo $testarray['test1'];
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • Just a note: in that specific case, nothing will be printed in the page since `echo false;` shows nothing. – FirstOne Jul 02 '16 at 16:47
0

if you want to reach first element of any (indexed or associative) array_

you can use current method,

for your case;

echo current($testarray);