'php is variable an array or object

Trying to figure out how to do the equivalent of something I did in javascript but in php. But I'm not sure of the operators to do it. In javascript I wanted to see if a particular parameter being passed was either an object or array.. and if not then was it a string/int and what I did was something like

if (str instanceof Array || str instanceof Object) 
{
   //code
}
else
{
   //code
}

anyone know of the equivalent to this for php?



Solution 1:[1]

Use is_array to check if a variable is an array, and similarly, use is_object to check if a variable is an object.

Solution 2:[2]

Try to use:

if (!is_scalar($var)) {
    // Varible is object or array
}

Solution 3:[3]

I came across this question while looking for is_countable. Maybe it's of some use to somebody. https://www.php.net/manual/en/function.is-countable.php

Solution 4:[4]

object (use is_object)-----

stdClass Object
(
    [rest_food_items_id] => 137
    [rest_user_id] => 42
)

array (use is_array)----

Array
(
    [rest_food_items_id] => 137
    [rest_user_id] => 42
)

**

Example

**

if(is_object($data)){

}
if(is_array($data)){

}

Solution 5:[5]

As of PHP 8.0, you can use Union types when writing functions. It is not a direct answer to the question, but it may help someone:

function test(array|object $something): void
{
    // Here, $something is either an array or an object
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ry-
Solution 2 WOLFF
Solution 3 Yani
Solution 4
Solution 5 MAChitgarha