0
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $user_id = $row["user_id"];
    $user_name = $row["user_name"];
}

foreach ($array as $arr) {
    echo $arr;
}

Above code echos all the values from the $array how can I get a specific value of this array.
For example something like this echo $arr[2] (but it doesn't work)

Please mention that I'm getting some data from mysql and my purpose by asking this question is to get each value from a column separately. Thank you if you can help me.

1
  • Your question is not clear. You have declare '$array', but you are not using it. Then why you declare that? And other hand '$row' itself an array no need to copy that array into another array. Commented Jul 4, 2016 at 11:02

5 Answers 5

1

You forgot to fill your array with data...

while($row = mysqli_fetch_assoc($result)){
            $array[]= array($row["user_id"], $row["user_name"]);
        }

And now you can access to your data

 foreach($array as $arr){
  echo $arr[0];
  echo $arr[1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you need to get the specific value of an array. you can get by

$array[2]

not

$arr[2]

1 Comment

Cooool :) Silly mistakes may happen sometimes.!!
0

Please try

$array = array();
 while($row = mysqli_fetch_assoc($result)){
            $array[] = $row;
        }

foreach($array as $arr){
  print_r($arr);
}

Comments

0
$array = array();
while($row = mysqli_fetch_assoc($result)){
  $user_id = $row["user_id"];
  $user_name = $row["user_name"];
  $array[] = $row;
}

And use $array[2] to get records in 2nd index.

OR

foreach($array as $arr){
      echo $arr[0];
      echo $arr[1];
}

Comments

0

Also useful is to use the $key=>$value in your foreach loop.

foreach ($array as $key=>$value) {
    echo $key."->".$value."<br />";
}

This will list each of your array items with values and respective keys.

Comments

Your Answer

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