How to Find if an Array is Indexed or Associative in PHP?

Problem:

You have an array which has some elements inside. You want to check whether the array is an associative array or an indexed array.

Solution:

If any of the keys inside an array is a string, we’ll consider this as an associative array; otherwise, it is an indexed/sequential/numeric array. To test this, we’ll go through the following steps-

  1. Retrieving all the keys from the array, we’ll make a new array. (using array_keys() function)
  2. Test if the first value of the new array is a string (using is_string() function)
  3. Repeat this string test to all the elements (using array_map() function)
  4. If at least one value is string, then it is an associative array (using in_array() function).

 

<pre>
<?php
$test = array(100, 2, "Sunday", 50, 999);
echo in_array(1, array_map('is_string', array_keys($test))) ? "An associative array" : "An sequential(indexed) array";

echo "<br />";

$test = array(100, 2, "day"=> "Sunday", 50, 999);
echo in_array(1, array_map('is_string', array_keys($test))) ? "An associative array" : "An sequential(indexed) array";
?>
</pre>

[wpdm_file id=64]

Output:
An sequential(indexed) array
An associative array

How it works:
Taking all the keys of the $test[] array, array_keys() function creates an array. Note that the elements/values of the new array are now the keys of the $test[] array.The array_map() function applies is_string() function to all the elements of the new array. In other words, every element of the new array will be tested if it is a string. If the function finds any of the values as a string then it will return 1(true), otherwise 0(false). With these values(0 or 1), another array will be created.

With the in_array() function we’ll check if there is a 1 inside the array. If founds then it is an associative array, otherwise indexed/numeric array.

Note: This solution can only work on uni-dimensional array, not on multi-dimensional array.