PHP array help needed!?

Connor L

New member
$split = explode(";;", $file);
//Build locations
$locations = array();

for($i = 1; $i < count($split); $i ++)
{
$tempSplits = explode("&", $split[$i]);
array_push($locations, $tempSplits[1]."&&".$tempSplits[2]);
}

It keeps giving me an error saying:

Notice: Undefined offset: 0 in C:\wamp\www\genKml.php on line 16

Notice: Undefined offset: 1 in C:\wamp\www\genKml.php on line 16

But when I used the echo function and the same $tempSplit[1] and 2. It returned the correct output. I'm really confused here.
 
I think your problem is more to be validation. Is there any case where the explode of '&' does not happen? For instance, a $split[$i] that does not have a '&' in the string to be exploded?


$split = explode(';;', $file);
$locations = array();

$size = count($split);

for ($index = 0; $index < $size; ++$index)
{
$tempSplits = explode('&', $split[$index]);
$toBePushed = '';
if (!empty($tempSplits[0])
{
$toBePushed = $tempSplits[0];
}

if (!empty($tempSplits[1])
{
$toBePushed .= "&&{$tempSplits[1]}";
}

array_push($locations, $toBePushed);
}

Anyway, if you are merely replacing '&' for '&&' my suggestion is for you to do a simple string replacement:

for ($index = 0; $index < $size; ++$index)
{
$locations[] = str_replace('&', '&&', $split[$index]);
}

Hope it helps
 
I've found that sometimes PHP gets confused when you try to do processing like string concats in the middle of function calls.

Try using [] instead of the array_push function:

for($i = 1; $i < count($split); $i ++)
{
$tempSplits = explode("&", $split[$i]);
$locations[] = $tempSplits[1]."&&".$tempSplits[2];
}

(This should be faster too!)

Hope this helps
 
Back
Top