Jump to content

Undefined offset: 1


chris22

Recommended Posts

I have the following code:

 

<?php

$lines = count(file("input.txt"));

$file = fopen("input.txt", "r");



for($i=0; $i<=$lines; $i++)
{

$friend = fgets($file);

$friendInfo = explode(" ", $friend);


$friendID[$i] = $friendInfo[0];
$friendLAT[$i] = $friendInfo[1];
$friendLONG[$i] = $friendInfo[2];

echo $friendInfo[2];
echo $friendLAT[$i];


}

fclose($file);
?>

 

The value of $friendInfo[2]; and $friendLAT[$i]; echo out alright. However I get the following output:

 

0.0 0.0-10.1 10.112.2 -12.238.3 38.3179.9979.99

Notice: Undefined offset: 1 in C:\inetpub\wwwroot\test.php on line 18

 

Notice: Undefined offset: 2 in C:\inetpub\wwwroot\test.php on line 19

 

Notice: Undefined offset: 2 in C:\inetpub\wwwroot\test.php on line 21

 

It doesn't make any sense to me, I can assign the value of the array to a variable ($friendLAT[$i];), but it says the offset is undefined.

Link to comment
https://forums.phpfreaks.com/topic/231658-undefined-offset-1/
Share on other sites

I looked at your code and the following might be a better way of doing what I think you're trying to do...

<?php
$file = file("input.txt");
$friends = array();
foreach ($file as $line) {
        $friend = trim($line);
        $friendInfo = explode(" ", $friend);
        $friends[$friendInfo[0]] = array('lat'=>$friendInfo[1],'long'=> $friendInfo[2]);
}
print_r($friends);
?>

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/231658-undefined-offset-1/#findComment-1192182
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.