I have a query that returns either an object or an array based on the number of items. If there are zero or one items being returned, then it returns the item as an object. If there are two or more items, then it returns an array of objects.
I'm wanting to do a foreach
on the query result, but that is throwing an error if it is an object that is returned, rather than an array. So I've created a function that would convert an object to an array.
function to_array($unknown) {
if (count($unknown) === 0) {
$array=array($unknown);
} elseif (!is_array($unknown)) {
$array = array();
$array[0] = $unknown;
} else {
$array = $unknown;
}
return $array;
}
It can be used by simply calling $query_array = to_array($query_return)
.
Is this be best way to do this? Is there a better way? Might this create any problems?