PHP

Display array values

How can you display array values in PHP?

In PHP, you can display the values of an array using several methods, depending on the context. Below are some of the most common ways to display array values:

1. Using implode:

PHP
<?php
$cars = array('1. Volkswagen', '2. Toyota', '3. Mercedes', '4. Ford', '5. BMW');
echo implode(', <br />', $cars);
?>

Output:

1. Volkswagen,
2. Toyota,
3. Mercedes,
4. Ford,
5. BMW

2. Using foreach Loop

PHP
<?php
$array = ['1. Volkswagen', '2. Toyota', '3. Mercedes', '4. Ford', '5. BMW'];
foreach ($array as $value) {
echo $value . "<br>";
}
?>

3. Accessing Associative Array Values

PHP
$array = [
 "First Name" => "Jane",
 "Last Name" => "Doe",
 "Age" => 45,
 "City" => "Amsterdam"
];
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br>";
}

Output:

First Name: Jane
Last Name: Doe
Age: 45
City: Amsterdam