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:
php
php
php
- Sequential (Indexed) arrays
- Associative arrays
- Multidimensional arrays
<?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:
Associative arrays: The arrays which are having string type keys instead of indexes or which exist in ('key', 'value')pairs are called associative arrays.
January February March
<?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:
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.
January February March
<?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:
Note:
Array is associative
- === 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.