Friday, October 24, 2025
HomeLanguagesHow to check an array is associative or sequential in PHP?

How to check an array is associative or sequential in PHP?

In PHP there is no need to write the variable type before the variable because it is loosely-typed. It takes datatype from user defined values that are stored in it. Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data.
There are basically three types of arrays in PHP:

  • Sequential (Indexed) arrays
  • Associative arrays
  • Multidimensional arrays

Sequential Arrays: Those arrays which have numerical indexes in an ordered sequential manner (starting from 0 and ending with n-1) are called Sequential or Indexed arrays. In PHP, by default array Indexed array.




<?php
// Example of sequential array
  
$arr = array("January", "February", "March");
  
// 1st element
echo $arr[0] . "\n";
  
// 2nd element
echo $arr[1] . "\n";
  
// 3rd element     
echo $arr[2] . "\n";
?>


Output:

January
February
March

Associative arrays: The arrays which are having string type keys instead of indexes or which exist in (‘key’, ‘value’)pairs are called associative arrays.




<?php
// Example of associative array
  
$arr1= array("Month1" => "January",
             "Month2" => "February",
             "Month3" => "March" 
        );
  
echo $arr1["Month1"] . "\n";
echo $arr1["Month2"] . "\n";
echo $arr1["Month3"] . "\n";
?>


Output:

January
February
March

How to check if PHP array is associative or sequential?
There is no inbuilt method in PHP to know the type of array. If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array.




<?php
// Example to check Sequential array
  
// Associative array
$arr1= array("Month1" => "January",
             "Month2" => "February", 
             "Month3" => "March" 
        );
      
// Checking for sequential keys of array arr
if(array_keys($arr1) !== range(0, count($arr1) - 1))
    echo "Array is associative"; 
else
    echo "Array is sequential \n";
?>


Output:

Array is associative

Note:

  • === It returns True if $x and $y are equal and same type.
  • !== It returns True if $x and $y are not equal or not same type.
  • == It returns True if $x and $y are equal.
  • != It returns True if $x not equal to $y.
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS