is_array() Function in PHP: Complete Guide with Examples
When working with PHP, it’s important to validate data types to avoid errors. One common requirement is checking whether a variable is an array. This is where the is_array()
function becomes very useful.
In this article, we will cover:
- What is
is_array()
in PHP? - Syntax of
is_array()
- Practical examples
- Real-world use cases
- FAQs about
is_array()
What is is_array()
in PHP?
The is_array()
function in PHP is used to check whether a variable is an array or not.
It returns:
TRUE
if the variable is an array.FALSE
if it is not.
Why use is_array()
?
When handling user input, API data, or database results, it’s important to confirm the data type before processing it. is_array()
helps prevent runtime errors by ensuring you're dealing with an array before performing array operations.
Syntax of is_array()
bool is_array(mixed $variable)
- Parameter:
$variable
– The variable you want to check.
- Return Type:
bool
– ReturnsTRUE
if the variable is an array,FALSE
otherwise.
Examples of is_array()
in PHP
Example 1: Basic Usage
<?php
$data = [1, 2, 3];
if (is_array($data)) {
echo "Yes, it is an array.";
} else {
echo "No, it is not an array.";
}
?>
Output:
Yes, it is an array.
Example 2: Checking a String
<?php
$data = "Hello, World!";
if (is_array($data)) {
echo "It is an array.";
} else {
echo "It is not an array.";
}
?>
Output:
It is not an array.
Example 3: Checking an Empty Array
<?php
$data = [];
if (is_array($data)) {
echo "It is an array, but empty.";
} else {
echo "It is not an array.";
}
?>
Output:
It is an array, but empty.
Note:
Even if the array is empty, is_array()
still returns TRUE
.
Real-World Use Case for is_array()
Imagine you are receiving data from an API. Sometimes the API might return a single object instead of an array of objects. You can safely handle this using is_array()
:
<?php
$response = getApiResponse(); // Assume this function gets the API data
if (is_array($response)) {
foreach ($response as $item) {
echo $item['name'] . "<br>";
}
} else {
echo "Unexpected response format.";
}
?>
FAQs About is_array()
in PHP
Q1: Is an object considered an array in PHP?
Answer: No. Objects are a different data type. is_array()
will return FALSE
for objects.
Q2: What happens if you pass NULL
to is_array()
?
Answer: It will return FALSE
because NULL
is not an array.
Q3: How is is_array()
different from gettype()
?
Answer: is_array()
is a direct check for arrays and returns a boolean (TRUE
or FALSE
), while gettype()
returns a string representing the type ("array"
, "string"
, etc.).
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.