Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daniel1836's avatar

How to return Multiple values from a while loop from an SQL query.

I have an issue where I have a function like this which outputs:

      while ($row = mysqli_fetch_array($sql_result)) {
           $division_name = stripcslashes($row['name']);
           return  $division_name;

    }

This works to fetch a single value, but it doesn't when I need multiple values from the query. (in that case it only returns the first match row).

If I substitute return for echo, I get unexpected behaviour from my view.

How can I structure my code so that when I call this function, it outputs multiple values properly.

Thanks

0 likes
7 replies
Charizard's avatar

you can initialize an empty array and insert each row into the array in the while loop:

$array = [];
while ($row = mysqli_fetch_array($sql_result)) {
           $division_name = stripcslashes($row['name']);
           $array[] = $division_name;
    }

return $array;

your array will contain a list of all values you got from the query;

Daniel1836's avatar

Using an empty array works. But it only works with (print_r) which output the array indexes as well. I need the values to look good in the view. Using (return) prints the word "array" not the values.

Are there any other solutions/fixes?

Thanks for the replies.

Daniel1836's avatar

No procedural. The empty array works. I have "echo X" in the view and I call my function which uses (print_r), so I'm printing twice, which is making the view act unexpectedly, (return) doesn't have that problem, but doesn't work here so far.

frankielee's avatar

You might need to post your view(blade file), controller etc that are related.

Please or to participate in this conversation.