I have a php class that interacts with mysql database and then fetches an array as a result.
$res = $db->getResult(); // $res is an array
I use it with print_r :
print_r($res);
and it outputs this:
Array
(
[0] => Array
(
[id] => 1
[firstname] => Mohamed
[lastname] => Kadri
)
[1] => Array
(
[id] => 2
[firstname] => Slim
[lastname] => Nejmaoui
)
[2] => Array
(
[id] => 3
[firstname] => Sameh
[lastname] => Chraiti
)
And with foreach:
foreach ($res as $row) {
echo $row['id'] . ' ' . $row['firstname'] . ' ' . $row['lastname'] . '<br />';
}
it outputs this:
1 Mohamed Kadri
2 Slim Nejmaoui
3 Sameh Chraiti
but when there is only one row, it shows this:
1 1 1
M M M
K K K
(1 is the id, M is the first letter in the firstname and K is the first letter in the lastname).
So maybe when there is more than one row the class generates a multidimensional array and the foreach will work on it, and when there is only one row it generates a simple array that will be treated as a multidimensional array by this exact foreach.
So should I make a condition to process one of two types of foreach?
Thanks.
apparently your db object return a single array when you have only one result somthing like that:
you can test first input and if this is not an array don’t loop thrue the foreach else do a foreach
I think you should change your db class to always return a nested array even on single row result to keep your results consistents.