PHP Associative Arrays

An associative array is an array where each element is stored with a custom key rather than a numeric index.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);

var_dump($person);
?>
</body>
</html>

Try it yourself

Access Associative Arrays


Access elements using their keys:


Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);

echo $person["name"]."<br>"; // Outputs: Alice
echo $person["age"]; // Outputs: 30
?>
</body>
</html>

Try it yourself

Change Value


Modify elements by reassigning a value to an existing key:


Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
$person["age"] = 31; // Updates the value of "age" to 31

var_dump($person);
?>
</body>
</html>

Try it yourself

Looping Through an Associative Array


You can loop through an associative array using a foreach loop:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.