Tags
PHP , array
Asked 3 years ago
9 Jun 2021
Views 519
ruby-rails

ruby-rails posted

How to check if PHP array is associative or sequential?

How to check if PHP array is associative or sequential?
yogi

yogi
answered Feb 27 '23 00:00

In PHP, you can check if an array is associative or sequential by examining the keys of the array .

A sequential array has numeric keys that start at 0 and increase by 1 for each element. On the other hand, an associative array has non-numeric or non-sequential keys .

To check if an array is sequential, you can use the array_values() function to get an indexed array of the values, and then compare it with the original array using the === operator. If they are the same, then the array is sequential.

Here's an example code snippet:


function isSequential($arr) {
  return array_values($arr) === $arr;
}

To check if an array is associative, you can use the array_keys() function to get an array of the keys, and then use the array_filter() function to remove any numeric keys. If the resulting array is not empty, then the array is associative.

Here's an example code snippet:

function isAssociative($arr) {
  $keys = array_keys($arr);
  $nonNumericKeys = array_filter($keys, 'is_string');
  return count($nonNumericKeys) > 0;
}

You can use these functions to check whether an array is sequential or associative by passing the array as a parameter to the respective function.
Post Answer