PHP Associative Arrays

0
5K

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
Categories
Read More
Other
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser....
By PHP Tutorial 2024-05-17 07:10:53 0 4K
Other
الثورة البلوكتشين وتحولاتها في الصناعات المختلفة
مقدمة: شهدت تقنية البلوكتشين ثورة هائلة في السنوات الأخيرة، حيث أصبحت لديها القدرة على تغيير...
By MOHAMED ATTALLAH 2024-05-14 14:03:03 0 4K
Other
PHP Constants
Constants are like variables, except that once they are defined they cannot be changed or...
By PHP Tutorial 2024-05-17 07:39:53 0 4K
Other
PHP Associative Arrays
PHP Associative Arrays Associative arrays are arrays that use named keys that you assign to...
By PHP Tutorial 2024-05-17 08:01:14 0 5K
Other
PHP Nested if Statement
Nested If You can have if statements inside if statements, this is...
By PHP Tutorial 2024-05-17 07:47:26 0 2K