1

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);
?>
7
  • 1
    $temp=(int)fgets($file);, no? Commented Apr 29, 2014 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 ; Commented Apr 29, 2014 at 9:54
  • @raina77ow OP wants to store integers > INT_MAX, so needs to use string type. Commented Apr 29, 2014 at 9:57
  • @AndreschSerj , also works in echo eval.in/143690 Commented Apr 29, 2014 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"; Commented Apr 29, 2014 at 9:58

1 Answer 1

3

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

$temp = trim(fgets($file));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.