PHP Associative Arrays

0
9K

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

Căutare
Categorii
Citeste mai mult
Alte
PHP Variables Scope
PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a...
By PHP Tutorial 2024-05-17 07:18:52 0 11K
Alte
PHP Casting
Sometimes you need to change a variable from one data type into another, and sometimes you want a...
By PHP Tutorial 2024-05-17 07:38:02 0 4K
Alte
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an array or each...
By PHP Tutorial 2024-05-17 07:50:19 0 5K
Alte
PHP do while Loop
The do...while loop - Loops through a block of code once, and then repeats the loop as...
By PHP Tutorial 2024-05-17 07:49:22 0 5K
Alte
PHP - $_SERVER
$_SERVER $_SERVER is a PHP super global variable which holds information about headers,...
By PHP Tutorial 2024-05-17 08:08:50 0 8K
Sociallez https://sociallez.com