updated on: 19-Dec-2022
An array is a special variable, which can hold more than one value at a time.
In PHP, the array() function is used to create an array:
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP - Indexed Arrays</title>
</head>
<body>
<?php
// index always starts at 0
// $cars = array("Volvo", "BMW", "Toyota");
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
$cars[10] = "Toyota";
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
//
// Get The Length of an Array count()
//
echo "<br>Number of elements" . count($cars);
//
// Loop through an index array
//
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
array(
key => value,
key2 => value2,
key3 => value3,
…
)
Note: A short array syntax exists which replaces array() with [].
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
The key can either be an int or a string. The value can be of any type.
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP - Associative Arrays</title>
</head>
<body>
<?php
//Associative arrays are arrays that use named keys that you assign to them.
$age = array("ahmad"=>"35", "ali"=>"37", "hamza"=>"43");
/*$age['ahmad'] = "35";
$age['ali'] = "37";
$age['hamza'] = "43";*/
echo "Ahmad is " . $age['ahmad'] . " years old.";
//
//Loop Through an Associative Array
//
/*foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}*/
?>
</body>
</html>
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array), "\n";
}
next($array);
}
?>
Muhammad Yasir Bhutta