Mercy
Mercy

Reputation: 2271

How to identify a PHP variable is an array or not

How to check whether the PHP variable is an array? $value is my PHP variable and how to check whether it is an array?

Upvotes: 0

Views: 622

Answers (4)

TheCarver
TheCarver

Reputation: 19713

I'm adding a late answer here as I think I've got a better solution if people are using multiple array checks.

If you're simply checking a single array, then using PHP's is_array() does the job just fine.

if (is_array($users)) {
    is an array
} else {
    is not an array
}

However, if you're checking multiple arrays - in a loop for example - then there is a much better performing solution for this, using a cast:

if ( (array) $users !== $users ) {
    // is not an array
} else {
    // is an array
}

THE PROOF

If you run this performance test, you will see quite a performance difference:

<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>

THE RESULT

is_array  :  7.9920151233673
cast, === :  1.8978719711304

Upvotes: 0

Shoban
Shoban

Reputation: 23016

is_array — Finds whether a variable is an array

http://uk.php.net/is_array

Upvotes: 1

Sadegh
Sadegh

Reputation: 6854

php has function named is_array($var) which returns bool to indicate whether parameter is array or not http://ir.php.net/is_array

Upvotes: 3

rclanan
rclanan

Reputation: 98

echo is_array($variable);

https://www.php.net/is_array

Upvotes: 8

Related Questions