Jump to content

small array problem


pedrobcabral

Recommended Posts

<?php
$i =  array();
while($row = mysql_fetch_array($result)){
$i[$x] = $row['id'];
$x++;
}

echo "<pre>";
print_r($i);
echo "</pre>";
?>

 

This outputs the folowing:

 

Array

(

    [] => 3

    [1] => 4

    [2] => 9

)

 

Why the first it is not [ 0 ] ? Can't figure out the way to turn it that way. Thank you.

Link to comment
https://forums.phpfreaks.com/topic/44153-small-array-problem/
Share on other sites

The variable $x is not set during the first iteration of the loop. A better way to write this would be:

<?php
$i =  array();
while($row = mysql_fetch_array($result))
      $i[] = $row['id'];
?>

 

When you use "[]" with arrays, PHP assigns the value to the next numerical array index automatically. This will give you what you want.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/44153-small-array-problem/#findComment-214386
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.