0

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

0

4 Answers 4

8

echo is_array($variable);

https://www.php.net/is_array

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

is_array — Finds whether a variable is an array

http://uk.php.net/is_array

Comments

0

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

1 Comment

I'm sorry, but I'll stick with is_array. It very precisely describes what it does. The few microseconds you save on a single call is not worth the source code obfuscation. If you look at this code again in half a year you'll be scratching your head WTF you were trying to do here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.