shazia
shazia

Reputation: 179

array returns error undefined index in php

The index 4 exisits in array rating but i get error...if i undo the comments $write=4 then it works fine.

foreach($writers[$i] as $write)
      {
      echo "writer: $write  -  rating: ";
      print_r($rating);
//$write=4;
      echo "<br>". $rating[$write] ;

}

the above code gives

    writer: 4 
Notice: Undefined index: 4 in D:\wamp\www\shazia\CRM\EffortTrackUpload\admin\cron.php on line 232

The array rating gives:

Array ( [3] => 5.1 [4] => 6 [5] => 5.2 [6] => 5 [8] => 5 [9] => 5 [10] => 5 [11] => 4 [12] => 3.6 [13] => 5 [14] => 5.1 )

can anyone please help me explain what i am doing wrong.

Thanks

Upvotes: 0

Views: 822

Answers (4)

Gaurav
Gaurav

Reputation: 28755

foreach($writers[$i] as $write)
      {
      echo "writer: $write  -  rating: ";
      print_r($rating);
//$write=4;
      echo "<br>". $rating[trim($write)] ; // use trim so that it will replace " 4" to "4"

}

Upvotes: 0

Stephen
Stephen

Reputation: 18917

As per your comment, the issue is that $write is a string - " 4", but the array index is just an integer 4.

Work out why the 4 is padded with space in the $writers[$i] array, if you are getting the array from elsewhere you could use intval($write) to get the correct value.

Upvotes: 2

brian_d
brian_d

Reputation: 11385

Either $writers[$i] is undefined when $i = 4, or $rating[$write] is undefined when $write = 4. It will be whichever one is on line 232 corresponding to your error message.

Use if(isset($writers[$i])) to prevent the error.

Edit From your comment, I'd say it is $rating[4] that is undefined.

Upvotes: 1

FraserK
FraserK

Reputation: 302

foreach($writers as $write){
   //code here
}

Is how it should be written :)

Upvotes: -1

Related Questions