My problem is very specific. I'm a beginner php programmer and I'm having difficulty indexing the array datastructure in PHP. The program is reading from an input file (input.txt
) and storing the result into an array with key same as the item. Although the input.txt
files have numbers for convenience I have to store them as string ( My program needs integers of size greater than 32 bit). But when I try to index them as $a["3"]
I get an error Undefined offset: 3
. I tried $a['3']
, $a[3]
all with the same result. But curiously I am able to index last element in the array that is $a["2"]
correctly! Please help.
Here is the input text file :
3
4
5
1
2
Here is the code segment :
<?php
ignore_user_abort(true);
set_time_limit(0);
$temp=0;
$a= array();
$file= fopen("input.txt","r") or exit( "unable to open file");
while(!feof($file)){
$temp=fgets($file);
$a[$temp]=$temp;
}
fclose($file);
echo "<br>The array is .. ";
foreach ($a as $key => $item) {
echo "<br> Key => item =",$key."=>",$item ;
echo "<br>Manual array test ",$a["3"]; // This line demonstrates the problem.
}
echo "<br>Manual array test ",$a["2"]; // This one has no error! So basically only the last element is being indexed correctly
//echo "<br> No of 2 sums is ",twoSum($a,4,6);
?>
$temp=(int)fgets($file);
, no? – raina77ow Apr 29 at 9:48,
where you should use.
when you concat strings. For example here:echo "<br> Key => item =",$key."=>",$item ;
it should beecho "<br> Key => item =".$key."=>".$item ;
– Andresch Serj Apr 29 at 9:54,
also works inecho
eval.in/143690 – CodeBird Apr 29 at 9:58echo "a","b";
is correct, and will behave the same asecho "a"."b";
– Benubird Apr 29 at 9:58