PHP Associative Arrays

0
5KB

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

ExampleGet your own PHP Server

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
Try it Yourself »

Access Associative Arrays

To access an array item you can refer to the key name.

Example

Display the model of the car:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo $car["model"];
Try it Yourself »

Change Value

To change the value of an array item, use the key name:

Example

Change the year item:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
$car["year"] = 2024;
var_dump($car);
Try it Yourself »


Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example

Display all array items, keys and values:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

foreach ($car as $x => $y) {
  echo "$x: $y <br>";
}
Try it Yourself »

For a complete reference of all array functions, go to our complete PHP Array Reference.


PHP Exercises

Test Yourself With Exercises

Exercise:

Create an associative array containing the age of Peter, Ben and Joe.

$age = array("Peter""35", "Ben""37", "Joe""43");

Start the Exercise

Search
Nach Verein filtern
Read More
Other
PHP Introduction
PHP code is executed on the server. What You Should Already Know Before you continue you...
Von PHP Tutorial 2024-05-17 07:08:40 0 3KB
Other
PHP Strings
A string is a sequence of characters, like "Hello world!". Strings Strings in PHP are...
Von PHP Tutorial 2024-05-17 07:28:17 0 3KB
Other
تطورات التعلم الآلي وتأثيرها على مستقبل العمل
مقدمة: في ظل التطورات السريعة للتكنولوجيا والابتكار، أصبح التعلم الآلي...
Von MOHAMED ATTALLAH 2024-05-14 13:56:58 0 4KB
Other
PHP Multidimensional Arrays
In the previous pages, we have described arrays that are a single list of key/value pairs....
Von PHP Tutorial 2024-05-17 08:07:20 0 4KB
Other
PHP if Operators
Comparison Operators If statements usually contain conditions that compare two values....
Von PHP Tutorial 2024-05-17 07:45:46 0 2KB