TrueBlue TrueBlue - 2 months ago 8
PHP Question

Building an array gives PHP Undefined Offset: 0

I can probably find a way to work around this problem I am having, but would really like to understand what language construct is causing it.

The logic is as follows, I want to build up a Session variable as the user clicks on a route on Google Maps that is an array of waypoints. The POST packet is a JSON object:

?waypoint={"waypoint":[{"lat":"23.3","long":"145"}]}


The code that accepts the POST and interprets is:

<?php
session_start ();
//session_destroy();
//die;
//$waypoints[] = array(); <<== uncomment this and the behaviour changes
if (isset ( $_GET ['waypoint'] )) {
$waypoint = $_GET ['waypoint'];
$waypoint = json_decode($waypoint,true);
print_r($waypoint['waypoint']); <<<========output 1
if (isset ( $_SESSION ['waypoints'] )) {
$waypoints = $_SESSION ['waypoints'];
$waypoints [] = $waypoint['waypoint'];
$_SESSION ['waypoints']=$waypoints;
} else {
$_SESSION ['waypoints'] = $waypoint['waypoint'];
$waypoints[] = $waypoint['waypoint'];
}
}

foreach( $_SESSION ['waypoints'] as $var) {
var_dump($var); <<<<====== Output 2
echo($var[0]['lat']); <<<<==== Here is the problem.

};
?>


Here is the problem. The first time through, Output 1 and 2 give the outputs below and the correct value for lat is output = 23.3

**Output 1:** Array ( [0] => Array ( [lat] => 23.3 [long] => 145 ) )
-------------------------------------------------------
**Output 2:**
array (size=1)
0 =>
array (size=2)
'lat' => string '23.3' (length=4)
'long' => string '145' (length=3)


The second call, produces an error
Notice: Undefined offset: 0
and subsequent calls are fine, that is the array builds up as expected. Now if I uncomment the statement
waypoints[] = array();
It bombs on the first pass, yet all subsequent runs are okay.

Is anyone able to interpret this behaviour?

Thanks

Answer

The Issue

your issue is in the first line of the else condition that reads $_SESSION ['waypoints'] = $waypoint['waypoint'];.

The Fix

If you change it to $_SESSION ['waypoints'][] = $waypoint['waypoint']; then you should resolve the errors you are getting.

The Explanation

What you are looking for in echo($var[0]['lat']); is for the values of each waypoint to contain an array which they do when they are set in your if ($waypoints [] = $waypoint['waypoint'];) condition but not in your else condition ($_SESSION ['waypoints'] = $waypoint['waypoint'];)

Comments