(PHP 4, PHP 5)
is_array — Prüft, ob die Variable ein Array ist
Die zu untersuchende Variable.
Gibt TRUE zurück, wenn var vom Typ array ist, andernfalls FALSE.
Beispiel #1 Überprüfen, ob die Variable ein Array ist
<?php
$yes = array('dies', 'ist', 'ein Array');
echo is_array($yes) ? 'Array' : 'kein Array';
echo "\n";
$no = 'dies ist ein String';
echo is_array($no) ? 'Array' : 'kein Array';
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array kein Array
Note that in the following case, other than returning false, it will also produce an E_NOTICE
<?php
error_reporting(E_ALL | E_STRICT);
$emptyArray = array();
if (is_array($emptyArray[0]) === false) {
echo 'false returned';
}
?>
Output:
Notice: Undefined offset: 0 in test.php on line 5
false returned
I would change the order of the comparison, because if it is really an empty array, it is better to stop at that point before doing several 'cpu & memory intensive' function calls.
In the end on a ratio of 3 not empty arrays to 1 empty array computed for 1000000 iterations it needed 10% less time.
Or the other way round:
It needed approx 3% to 4% more time if the array is not empty, but was at least 4 times faster on empty arrays.
Additionally the memory consumption veritably lesser.
<?php
function is_assoc($array) {
return (is_array($array) && (count($array)==0 || 0 !== count(array_diff_key($array, array_keys(array_keys($array))) )));
}
?>
I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().
Cast the value to an array, then check (using ===) if it is identical to the original.
<?php
if ( (array) $unknown !== $unknown ) {
echo '$unknown is not an array';
} else {
echo '$unknown is an array';
}
?>
You can use this script to test the speed of both methods.
<pre>
What's faster for determining arrays?
<?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."
?>
</pre>
Prints something like:
What's faster for determining arrays?
is_array : 7.9920151233673
cast, === : 1.8978719711304
Tested 1000000 iterations.
<?php
function is_assoc($array) {
return (is_array($array) && (0 !== count(array_diff_key($array, array_keys(array_keys($array)))) || count($array)==0));
}
?>
because empty array is assoc. too
If you would like to be able to check multiple variables at the same time, similar to isset, use the following:
<?php
function isarray() {
$A = func_get_args();
foreach ($A as $k => $v) {
if (!is_array($v)) {
return false;
}
}
return true;
}
?>
Using empty() in the previous example posted by Anonymous will result in a "Fatal error: Can't use function return value in write context". I suggest using count() instead:
<?php
function is_assoc($array) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
?>
strictly speaking: array_diff_key does not return boolean, so using it in a comparison might eventually be considered 'bad'.
perhaps add a bit more cruft...?
<?php
function is_assoc($var)
{
return is_array($var) AND ! empty ( array_diff_key($var,array_keys(array_keys($var))));
}
?>
Or you could make use of the array_diff_key and array_key function:
<?php
function is_assoc($var)
{
return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}
function test($var)
{
echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}
// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);
// an array
$b = array_values($a);
test($b);
// an object
$c = (object)$a;
test($c);
// other types
test($a->a);
test($a->b);
test($a->c);
?>
The above code outputs:
I'm an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
Or you could make use of the array_diff_key and range functions:
<?php
function isVector($var) { return count(array_diff_key($var, range(0, count($var) - 1))) == 0; }
function isAssociative($var) { return !isVector($var); }
?>
yousef's example was wrong because is_vector returned true instead of false if the key was found
here is the fixed version (only 2 lines differ)
<?php
function is_vector( &$array ) {
if ( !is_array($array) || empty($array) ) {
return -1;
}
$next = 0;
foreach ( $array as $k => $v ) {
if ( $k !== $next ) return false;
$next++;
}
return true;
}
?>
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !== $v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an array is not suitable in my opinion and i think checking if the array is empty would also be a suitable check before the rest of the code runs.
So here's the modified (is_vector) version
<?php
function is_vector( &$array ) {
if ( !is_array($array) || empty($array) ) {
return -1;
}
$next = 0;
foreach ( $array as $k => $v ) {
if ( $k !== $next ) return true;
$next++;
}
return false;
}
?>
and the modified (alex's is_assoc) version
<?php
function is_assoc($_array) {
if ( !is_array($_array) || empty($array) ) {
return -1;
}
foreach (array_keys($_array) as $k => $v) {
if ($k !== $v) {
return true;
}
}
return false;
}
?>
Yet another simpler, faster is_assoc():
<?php
function is_assoc($array) {
foreach (array_keys($array) as $k => $v) {
if ($k !== $v)
return true;
}
return false;
}
?>
In my tests it runs about twice as fast as Michael/Gabriel's array_reduce() method.
(Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards. Michael solves this problem by comparing array_reduce() to count(), but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback).
Even if an array has only one value, it is still an array and is treated like one.
<?php
$arr[] = "I'm an array.";
if(is_array($arr))
{
foreach($arr as $val)
{
echo $val;
}
}
?>
The above code outputs:
I'm an array.
Hi.
My boolean function returns true, if all values in array are that same type (like in my funct. - it checks, if all are numeric).
<?php
function isNumArray($array)
{
$r = false;
if (is_array($array))
{
foreach($array as $n=>$v)
{
if (is_array( $array[$n] ))
{
$r = isNumArray( $array[$n] );
if ($r==false) break;
} else
if (!is_numeric($v))
{
$r=false;
break;
} else
$r=true;
}
}
return $r;
}
# example
$arr1 = array('34', 3.14, array('321', 092), '2', 55, -173, array('1.98', '-044'), '0');
$arr2 = array('3 4', 3.14, array('-321', 56, 0-92), '2', 55, true, array('zero44'), '0');
echo '1. '.(isNumArray($arr1) ? 'Only numz.' : 'Various values!')."\r\n".
'2. '.(isNumArray($arr2) ? 'Only numz.' : 'Various values!');
# return
# 1. Only numz.
# 2. Various values!
?>
A slight modification of what's below:
<?php
function is_assoc($array)
{
return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
}
function is_assoc_callback($a, $b)
{
return $a === $b ? $a + 1 : 0;
}
?>
Yet another safer, faster way of detecting whether an array is associative.
The principle is: using array reduction on the keys, we verify that each key is numeric and is equal to its rank.
Beware: integer keys that are not in sequence, or are negative, or with "holes", still make an associative array.
<?php
/**
* @param array $arr
* @returns boolean
*/
function isNotAssocArray($arr)
{
return (0 !== array_reduce(
array_keys($arr),
create_function('$a, $b', 'return ($b === $a ? $a + 1 : 0);'),
0
)
);
}
?>
Of course, it is still faster if the callback for array_reduce is not an anonymous function:
<?php
function callbackReduceNotArray($a, $b)
{
return ($b === $a ? $a + 1 : 0);
}
function isVector($arr)
{
return (0 !== array_reduce(
array_keys($arr),
'callbackReduceNotArray',
0
)
);
}
?>
Here's another way to see if an array is associative (nobody actually uses the term "vector" ;-) ). It's a little less breakable than the other current leading suggestion, and it's somewhat faster. Tested with 1000 iterations of two simple arrays (one associative, one not).
<?php
function array_is_associative ($array)
{
if ( is_array($array) && ! empty($array) )
{
for ( $iterator = count($array) - 1; $iterator; $iterator-- )
{
if ( ! array_key_exists($iterator, $array) ) { return true; }
}
return ! array_key_exists(0, $array);
}
return false;
}
?>
@elanthis at awesomeplay dot com, your function to check whether an array is a map or a vector has a little flaw.
Comparing $k != $value will return true if $value is 0. If you check a map containing just one element like array('foo'=>'bar') your check assumes that this is a vector. Use the operator !== (not identical with) to avoid that:
<?php
function is_vector (&$array) {
$next = 0;
foreach ($array as $k=>$v) {
if ($k !== $next)
return false;
$next++;
}
return true;
}
?>
If You want to del all slashes from database query result , try this function:
<?php
function no_slashes($array)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
$value=no_slashes($value);
$array_temp[$key]=$value;
}
else
{
$array_temp[$key]=stripslashes($value);
}
}
return $array_temp;
}
?>
Yet another associative array test:
<?php
function binary_nand ($a, $b) { return !$a && !$b; }
function binary_nor ($a, $b) { return !$a || !$b; }
// Returns true if array has elements with non-numeric keys
function is_associative_array ($arr) {
return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nor", true);
}
// Returns true if all elements of array have a non-numeric key
function is_strict_associative_array ($arr) {
return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nand", false);
}
?>
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.
The functions fail to recognize indexes that are not in sequence or in order. For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.
The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way. The result must match the array passed to it in order to truly be a numerically indexed (sequential) array. Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).
The following functions will work for PHP >= 4.
<?php
function is_sequential_array($var)
{
return (array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
}
function is_assoc_array($var)
{
return (array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
}
?>
If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.
Will check a Multi-Dimentional Array to any specified level. This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.
<?php
// checks for multiarray to defined depth level recursively
// original $level must be 2 or more, else will instantly return true
function isDeepMultiArray($multiarray, $level = 2) { // default is simple multiarray
if (is_array($multiarray)) { // confirms array
if ($level == 1) { // $level reaches 1 after specified # of recursions
return true; // returns true to recursive function conditional
} // end conditional
foreach ($multiarray as $array) { // goes one level deeper into array
if (isDeepMultiArray($array, $level - 1)) { // check subarray
$message = "I'm a multiarray"; // optional message
return $message; // best if $message = true so function returns boolean
} // end recursive function
} // end loop
} else { // not an array at specified level
return false; // is also used recursively so can't change to message
}
}
if (isDeepMultiArray(array(array()), 2)); // beware this returns true eventhough arrays are empty
?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
Simple check for a Multi-Dimentional Array of any depth
<?php
// checks for multiarray (2 or more levels deep)
function isMultiArray($multiarray) {
if (is_array($multiarray)) { // confirms array
foreach ($multiarray as $array) { // goes one level deeper
if (is_array($array)) { // is subarray an array
return true; // return will stop function
} // end 2nd check
} // end loop
} // end 1st check
return false; // not a multiarray if this far
}
?>
Will check a Multi-Dimentional Array to any specified level. This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.
<?php
// checks for multiarray to defined depth level recursively
function isDeepMultiArray($multiarray, $level = 2) { // default is simple multi-array
if (is_array($multiarray)) { // confirms array
if ($level == 1) { // is array only 1 level deep, hence not multiarray
return true;
} // end conditional
foreach ($multiarray as $array) { // goes one level deeper
if (isDeepMultiArray($array, $level - 1)) { // check subarray
return true;
} // end recursive function
} // end loop
} else { // not an array at specified level
return false;
}
}
?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
And here is another variation for a function to test if an array is associative. Based on the idea by mot4h.
<?php
function is_associative($array)
{
if (!is_array($array) || empty($array))
return false;
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
?>
I was looking at several of the other examples for testing if an array is associative and they seemed a little limited, or a little bulky. Here's my take on it, I think it's a nice balance:
<?php
function is_associative($array){
if (!is_array($array)) return false;
foreach(array_keys($array) as $key=>$value) {
if ($key != $value) return true;
}
return false;
}
?>
The idea being that the array_keys() function returns a non-associative array, so if the array you fed it wasn't associative, all the key/value pairs in the array of keys should be identical. Otherwise it must have been associative.
There is another example of check to associative array. (See below early versions.)
<?php
funciton is_assoc_array($var) {
return is_array($var) && !empty($var) && !preg_match('/^\d+$/', implode('', array_keys($var)));
}
?>
this is my attempt at writing a function that would check for a multi dimentional array. where $dim is the number of dimentions you are checking for and $array is of course the variable that is being check. i dont know if there's a better way out there, but this is what i do.
<?php
function is_multi_array($array,$dim)
{
if(($dim==1)&&(is_array($array)))
{
return 1;
}
foreach($array as $level2)
{
if(is_multi_array($level2,$dim-1))
{
return 1;
}
}
return 0;
}
?>
is_array() under PHP 5.0.2 will return FALSE when passed an object descended from the internal class interface ArrayAccess(http://www.php.net/spl) even though said object behaves as an array would in most instances.
I've found the following user function helpful with my own classes and functions that expect array(s) as arguments, but work fine with objects that behave as an array would.
<?php
function is_array_abled(&$x)
{
return (bool)($x instanceof ArrayAccess or is_array($x));
}
?>
Mike's function is quite cool, it is just the one, I was searching for. Using range is a great idea! But it's a bit long for me. Here is a shorter version:
<?php
function is_assoc_array($var) {
if (!is_array($var)) {
return false;
}
return array_keys($var)!==range(0,sizeof($var)-1);
}
?>
Or, if you don't want to type that much:
<?php
function is_assoc($var) {
return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}
?>
All arrays in PHP are associative arrays, but it is quite easy to treat an associative array just like it is a sequential array. However, when dealing with XML-RPC, it is necessary to know whether an array is associative or sequential, so I created this function.
It isn't perfect, since an associative array that just happens to have sequential, integer keys starting with 0 will 'look' exactly like a sequential array, and will fool this function.
<?php
/****************************************************************
* is_assoc_array tries to decide whether or not a given array *
* is an associative array, or a sequential array. Of course, no *
* such distinction is made by PHP, so it really just tests *
* whether or not a given array could possibly be a sequential *
* array. Since an associative array with sequential, integer *
* keys 'looks' just like a sequential array, this function will *
* be fooled. *
* *
* BUG: Associative arrays with sequential, integer keys 'look' *
* just like sequential arrays, and will be identified as such. *
* *
****************************************************************/
function is_assoc_array( $php_val ) {
if( !is_array( $php_val ) ){
# Neither an associative, nor non-associative array.
return false;
}
$given_keys = array_keys( $php_val );
$non_assoc_keys = range( 0, count( $php_val ) );
if( function_exists( 'array_diff_assoc' ) ) { # PHP > 4.3.0
if( array_diff_assoc( $given_keys, $non_assoc_keys ) ){
return true;
}
else {
return false;
}
}
else {
if( array_diff( $given_keys, $non_assoc_keys ) and array_diff( $non_assoc_keys, $given_keys ) ){
return true;
}
else {
return false;
}
}
}
?>