You are advised to check corresponding YouTube video at the end of this article.
Associative arrays in PHP are arrays that use named keys instead of numerical indexes. Each key in the array is associated with a specific value. They are also commonly referred to as "hashes" or "dictionaries" in other programming languages.
In an associative array, the keys can be any valid string or integer, and each key is unique within the array. You can access the values of an associative array by specifying the corresponding key, rather than an index number.
<?php
$fruits = array("Apples" => 5, "Oranges" => 12, "Grapes" => 25);
echo "Amount of Apples: " . $fruits["Apples"] . "<br>";
echo "Amount of Oranges: " . $fruits["Oranges"] . "<br>";
echo "Amount of Grapes : " . $fruits["Grapes"] . "<br>";
?>
This PHP script initializes an associative array called $fruits
with three key-value pairs: "Apples" => 5
, "Oranges" => 12
, and `"Grapes" => 25". The keys of the array are the names of the fruits, and the values represent the number of fruits available.
Then, the script uses the keys to access the values stored in the associative array using the square brackets notation. It prints out the number of Apples, Oranges, and Grapes using the echo
statement.
The "=>"
operator is used in associative arrays to assign a value to a specific key. The key is placed on the left side of the =>
operator, and the corresponding value is placed on the right side of the =>
operator. It is a way to define key-value pairs in an array. In the example above, the keys are "Apples", "Oranges", and "Grapes", and the corresponding values are 5, 12, and 25, respectively.
<?php
$fruits = array("Apples" => 5, "Oranges" => 12, "Grapes" => 25);
$len_of_fruits = count($fruits);
echo "Num of elements: " . $len_of_fruits . "<br><br>";
foreach ($fruits as $key => $value) {
echo "In array: $key, amount: $value <br>";
}
?>
This PHP script creates an associative array $fruits
with three key-value pairs. The keys are the names of different fruits and the values represent the number of those fruits.
Then the script uses the count()
function to get the number of elements in the array and prints it out.
After that, the script uses a foreach
loop to iterate over each key-value pair in the array. Within the loop, the variable $key
represents the key (fruit name) and $value
represents the value (number of fruits). The script prints out the key and value for each iteration of the loop.
This way of iterating over an associative array in PHP is commonly used when you need to work with both the keys and values of the array.
No comments:
Post a Comment