John Davidson

php - Trying to return an itm from an Array or an Object


I have an issue... and i'm going crazy!

I get a object, in a variable (with Laravel, but it doesn't matter).

$searchImage = ListTypeImage::find($v->list_image_id);
return gettype($searchImage)

It returns Object.

The object:

"id": 15,
"titre": "Mariage 1",
"list_type_id": 2,
"image": "list\/sXoW4ZFzff0AuvSviIXFtHSrLy0SdTdq6shiBEpB.jpg",
"created_at": "2021-06-02T12:58:41.000000Z",
"updated_at": "2021-06-02T12:58:41.000000Z"

When i write:

return $searchImage->image;

It returns "list/sXoW4ZFzff0AuvSviIXFtHSrLy0SdTdq6shiBEpB.jpg"

But when i write:

$image = $searchImage->image;

It returns an error: Trying to get property 'image' of non-object

I have the same issue with an array. If i convert my object into a array:

 return $searchImage['image'];

It returns "list/sXoW4ZFzff0AuvSviIXFtHSrLy0SdTdq6shiBEpB.jpg"

And if i wrote:

 $image = $searchImage['image'];

I have this error: Trying to access array offset on value of type null

Should I change my job?
Thanks a lot!

The entire code:

private function getImageOfSharedList($id)
$return = ListTypeImage::find($id);
$return = json_decode($return);
return $return->image;

$image = $this->getImageOfSharedList($v->list_image_id);

My Answer:

I need to get an item from this object, but sometimes it's an array and sometimes it's an object. How can I handle this situation?

Here's a possible solution using PHP:

// Check if $searchImage is an array
if (is_array($searchImage)) {
// Get the first item from the array
$item = reset($searchImage);
} else {
// Get the item from the object
$item = $searchImage;

// Now you can access the properties of the item
echo $item->property_name;

This code first checks if `$searchImage` is an array using the `is_array()` function. If it is an array, it gets the first item from the array using the `reset()` function. If it is not an array, it directly assigns the object to the `$item` variable.

After that, you can access the properties of the item using the `->` operator.

Rate this post

3 of 5 based on 1960 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us