S
S
Shizz2011-05-19 14:16:40
PHP
Shizz, 2011-05-19 14:16:40

Determining array associativity, php

The question is quite simple, but the solution is a bit tricky.
There are two arrays: You need to determine if the array is associative or not. The first array is identical The first thing that comes to mind is to take array_keys() from the array and check the last key against the value of sizeof($array) - 1. This solution is quite simple, but may work with errors. There is no desire to iterate over the keys. That's why I decided to write here. Are there better and faster options?
array('a','b','c');
array('x'=>'a','y'=>'b','z'=>'c');

array(0=>'a',1=>'b',2=>'c');

Answer the question

In order to leave comments, you need to log in

9 answer(s)
A
Aux, 2011-05-19
@Aux

There are no non-associative arrays in PHP. So it's just a pass.

V
Vadim, 2011-05-26
@MisterX

A good option is made in Kohana,
/**
* Tests if an array is associative or not.
*
* @param array array to check
* @return boolean
*/
public static function is_assoc(array $array)
{
// Keys of the array
$keys = array_keys($array);
// If the array keys of the keys match the keys, then the array must
// not be associative (e.g. the keys array looked like {0:0, 1:1...}).
return array_keys($keys) !== $keys;
}

H
Hast, 2011-05-19
@Hast

What is an associative array? An array can have both index and associative keys. If you want all keys to be associative, then something like this:
$assoc = true;
foreach ($array as $key => $element)
{
if (is_numeric($key)) $assoc = false;
break;
}

A
Alexey Shein, 2011-05-19
@conf

Excuse me, but why do you need it?

I
Iskander Giniyatullin, 2011-05-19
@rednaxi

how do you want to catch arrays like

array(0=>'a', 1=>'b', 'c'=> 'd', 3=>'e');

without going through the entire array?
There will be a pass through the entire array in any case, otherwise there is no way to check it (unless you have 100% confidence in the project that if “the last key corresponds to the value of sizeof ($array) - 1” then the array is “not associative”)

G
Gregory, 2015-07-15
@grigruss

Might be useful to someone:

if(is_numeric(array_search($a[0], $a))){
    echo "Не ассоциативный";
}else{
    echo "Ассоциативный";
}

E
Evgeny Vasin, 2016-07-23
@eugen81

And if so?

function is_assoc(array $array) {
    return !empty(preg_grep('/[^0-9]/', array_keys($array)));
}

K
Kirill Nefediev, 2020-06-04
@Traineratwot

here is an option that is more accurate than checking only the first key but not as gluttonous as checking all keys

function isAssoc(&$arr = []): bool
    {
      $c = count($arr);
      if ($c > 10) {
        return !(array_key_exists(0, $arr) and array_key_exists(random_int(0, $c - 1), $arr));
      } elseif ($c > 0) {
        return !(range( 0, count($arr) -1 ) == array_keys( $arr ));
      }
      return FALSE;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question