Innn Innn - 7 months ago 15
PHP Question

Why return of get() function in laravel is not array when check with is_array

I am just very new to laravel and today I have run some code and get stuck at this code.

$topic = topic::where('id', $id)->get();
if(is_array($topic)){
echo 'yes';
}
else{
echo 'no';
}


The result is 'no' but I can "foreach" loop through each topic.

As I unserstand, 'Foreach' accepts only array parameter but if it's a real array why is_array return "no"?

Answer

Because it's not an array. It's a collection.

You can convert it to an array with toArray() method:

$topic = topic::where('id', $id)->get()->toArray();