Check if Variable is Array in PHP

Using the is_array() function

To check if variable is array in PHP, use is_array() function. The is_array() function is a built-in function in PHP that takes a variable as an argument and returns a Boolean value indicating whether the variable is an array.

Here is an example of how to use this function:

Output

We used is_array() function to check if variable is array or not.

is_array() function takes one argument – the variable we want to check – and returns a Boolean value.

Using the gettype() function

The gettype() function is another built-in function in PHP that takes a variable as an argument and returns a string indicating the type of the variable.

To check if a variable is an array, you can compare the return value of the gettype() function with the string "array".

Here is an example of how to use this approach:

Output

Using the typesetting syntax

PHP allows you to use typecasting syntax to convert a variable to a specific data type. To check if a variable is an array, you can use the (array) typecasting syntax to convert the variable to an array.

Here is an example of how to use the typesetting syntax to check if variable is array.

Output

If the variable is already an array, the typecasting syntax will have no effect.

If the variable is not an array, the typecasting syntax will convert the variable to an empty array. Therefore, if the typecasted value is equal to the original value, then the variable is an array. Otherwise, it is not.

That’s all about how to check if variable is array in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *