Answer the question
In order to leave comments, you need to log in
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
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;
}
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;
}
how do you want to catch arrays like
array(0=>'a', 1=>'b', 'c'=> 'd', 3=>'e');
Might be useful to someone:
if(is_numeric(array_search($a[0], $a))){
echo "Не ассоциативный";
}else{
echo "Ассоциативный";
}
And if so?
function is_assoc(array $array) {
return !empty(preg_grep('/[^0-9]/', array_keys($array)));
}
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 questionAsk a Question
731 491 924 answers to any question