PHP - Getting Started with key value pairs

by
Jeremy Canfield |
Updated: May 25 2024
| PHP articles
Let's say you want to create the following key:value pairs.
Key | Value |
---|---|
Name | Jeremy |
ID | 123456 |
Occupation | Engineer |
Arrays are used to create key value pairs.
$array = array(
"name" => "Jeremy",
"id" => "123456",
"occupation" => "engineer"
);
var_dump can be used to print the data structure of the array.
var_dump($fruit);
Which will return the following.
array(3) { [name]=> string(6) "Jeremy" [id]=> string(6) "123456" [occupation]=> string(8) "engineer" }
Specific elements can be printed, like this.
echo "array[name] = " . $array[name] . "<br />";
echo "array[id] = " . $array[id] . "<br />";
echo "array[occupation] = " . $array[occupation] . "<br />";
Which will return the following.
array[name] = Jeremy
array[id] = 123456
array[occupation] = engineer
Or you can loop through the array.
foreach ($array as $value) {
echo "$value<br \>";
}
Which will return the following.
Jeremy
123456
engineer
And here is how to print both the keys and values.
foreach ($array as $key => $value) {
echo $key . ' = ' . $value . '<br \>';
}
Which should return the following.
Name = Jeremy
ID = 123456
Occupation = engineer
Did you find this article helpful?
If so, consider buying me a coffee over at