Home » Php » PHP function foreach/while loop save multiple or array of values

PHP function foreach/while loop save multiple or array of values

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have this code which I want to save all of the column values taken from Mysql database.

<?php
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
    $data=$db->query("select * from item");
    foreach($data as $k=>$v){
    return $v['item_name'];
    }
}
echo itemName($db); //output:item1
?>

The problem is above code only returned the first row of data. Although I can use echo inside of the foreach loop like “echo $v[‘item_name’];”, then call the function which will output all the values like item1 item2 item2 etc. My question is how can I use return to save all off the values equivalent like echo does, but not immediately echoed out.

How to&Answers:

Collect data in array and return this array from your function:

$db = mysqli_connect('localhost','mysqluser','password','test');

function itemName($db){
    $data=$db->query("select * from item");
    $result = [];
    foreach($data as $v){
        $result[] = $v['item_name'];
    }
    return $result;
}

print_r(itemName($db));