Voting

: min(six, six)?
(Example: nine)

The Note You're Voting On

Daniel
5 years ago
The next post is not correct because has problems with blank array index:
https://www.php.net/manual/es/function.is-array.php#89332

The next code use the above link php code

<?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);

// maybe assoc array?
$b = array(0 => "aaa", 1 => 1, 3 => true); // Index 2 not exist
test($b);
?>

# Output
I'm an assoc array.
I'm an assoc array.

"Associative arrays are arrays that use named keys that you assign to them."
https://www.w3schools.com/php/php_arrays.asp

Solution:

<?php
function is_assoc(array $array)
{
return
count(array_filter(array_keys($array), 'is_string')) > 0;
}
function
test(array $array)
{
echo
is_assoc($array) ? "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(0=>"aaa",1=>1,3=>true);
test($b);
?>

# Output
I'm an assoc array.
I'm not an assoc array.

If you want check pure assoc. array replace > 0 by === count($array)

<< Back to user notes page

To Top