Check if a variable is an array or not in PHP

We often need to store an array in a variable. So here in this post, I am going to let you know how you can check whether a variable is an array or not in PHP.

So let’s continue following this tutorial…

PHP has an in-built is_array() function which can be used to do our task easily just within few lines of code. If the variable we pass in this function is an array, then it will return TRUE. If it is not an array, then the returned value will be FALSE.

Now we can simply use the PHP if-else statement to check if our variable is an array or not.

Before I go further, it’s time to see an example. Below is our PHP code:

<?php 

$arr = array(
  "red",
  "blue",
  "green",
  "pink",
);


if (is_array($arr))
{
  echo "This is an array";
} else {
  echo "This is not an array";
}

?>

I hope, you can understand what I did actually. But still, let me explain in brief…

In the code you can see above, we have first take a PHP variable and assign an array to it.  After that, we are using the is_array() function and checking it using the if-else statement.

In our case, we will see “This is an array” as the output:

This is an array

If the variable is not an array, then it will show “This is not an array” on our web page.

Also, read:

 

Leave a Reply

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