Basic
Advanced
Examples
PHP 8 - Array
Last modified: April 02, 2022Array is a variable that holds more than one values in on single variable. For example below which holds list of Country in $countries variable.
<?php
$countries = array("HK", "UK", "USA");
//or you can use below
// index start with 0 not 1
$countries[0] = "HK";
$countries[1] = "UK";
$countries[2] = "USA";
?>
1. Numeric Arrays
- Numeric arrays use number as access keys.
<?php
$subjects = array("Math", "English", "Biology")
//to access Numeric Arrays, we pass the index (start from 0)
echo "I study" . $subjects[0]. ",". $subjects[1]. ",". $subjects[2];
//we use . to join the strings
?>
2. Associative Array
- Associative Array use id key as access key
<?php
$marks = array("Math" => "80", "English" => "90", "Biology" => "99");
//or you can use below
$marks['Math'] = "80";
$marks['English'] = "90";
$marks['Biology'] = "99";
//to access a item in array
echo $marks["Math"]
?>
3. Multi-dimensional arrays
- These are arrays that contain other nested arrays.
Country | continent |
---|---|
China | Asia |
Nepal | Asia |
India | Asia |
UK | Europe |
France | Europe |
<?php
$countries = array (
"Asia" => array("China", "Nepal", "India"),
"Europe" => array("UK", "France"),
);
//to access Asia first country
echo $countries[0][0];
?>
3. Arrays Sorting
Sort Array in Ascending Order - sort()
<?php
$countries = array("HK", "UK", "USA");
sort($countries);
?>
Sort Array in Descending Order - rsort()
<?php
$countries = array("HK", "UK", "USA");
rsort($countries);
?>
Sort Array (Ascending Order), According to Value - asort()
<?php
$marks = array("Math" => "80", "English" => "90", "Biology" => "99");
asort($marks);
?>
Sort Array (Ascending Order), According to Key - ksort()
<?php
$marks = array("Math" => "80", "English" => "90", "Biology" => "99");
ksort($marks);
?>
Sort Array (Descending Order), According to Value - arsort()
<?php
$marks = array("Math" => "80", "English" => "90", "Biology" => "99");
arsort($marks);
?>
Sort Array (Descending Order), According to Key - krsort()
<?php
$marks = array("Math" => "80", "English" => "90", "Biology" => "99");
krsort($marks);
?>