array-php
array-php
md 12/19/2022
PHP
PHP
Array PHP
Download PDF
Download examples code
What is an Array?
An array is a special variable, which can hold more than one value at a time.
Array Types
Example #1
<!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()
//
//
// Loop through an index array
//
$arrlength = count($cars);
Associative Array
Syntax
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Note: A short array syntax exists which replaces array() with [].
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
2/5
array-php.md 12/19/2022
];
?>
The key can either be an int or a string. The value can be of any type.
Example #2
<!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";*/
?>
</body>
</html>
current
next
3/5
array-php.md 12/19/2022
<?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';
?>
key
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
4/5
array-php.md 12/19/2022
Further reading
Web
Youtube
Facebook
Twitter
5/5