Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
?>
share|improve this question
1  
$temp=(int)fgets($file);, no? –  raina77ow Apr 29 at 9:48
1  
you should get syntax errors for using , where you should use . when you concat strings. For example here: echo "<br> Key => item =",$key."=>",$item ; it should be echo "<br> Key => item =".$key."=>".$item ; –  Andresch Serj Apr 29 at 9:54
    
@raina77ow OP wants to store integers > INT_MAX, so needs to use string type. –  Benubird Apr 29 at 9:57
    
@AndreschSerj , also works in echo eval.in/143690 –  CodeBird Apr 29 at 9:58
    
@AndreschSerj No, actually echo can take multiple arguments, so echo "a","b"; is correct, and will behave the same as echo "a"."b"; –  Benubird Apr 29 at 9:58

1 Answer 1

New line value is also getting stored in $temp, trim the $temp data as below and try

$temp = trim(fgets($file));
share|improve this answer
    
Thanks a ton buddy! –  Jeevan B. Manoj Apr 29 at 11:04
    
You are welcome, glad it worked. –  Manoj Yadav Apr 29 at 11:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.