Get Key Value Pair From an Associative Array Using PHP

Last Updated on January 5, 2021 by Roshan Parihar

In this tutorial, learn how to get key value pair from an associative array in PHP. The short answer is: use the PHP foreach loop to traverse through each element and find the combination of keys and its relevant values.

You can also use the PHP for loop to access the elements of an associative array. However, it requires to find the length of the associative array to parse through all the items”.

The associative array contains the elements that have manually assigned keys of string type. Each key is manually defined by the users. Let’s find out how to access the combination of pairs with the examples given below:

Get Key Value Pair From an Associative Array Using PHP Foreach Loop

To get the key-value pair from an associative array, you can use the PHP foreach loop. It takes an argument as the associative variable and the $key => $value to find the items of the array in PHP. The loop traverses through all the elements to find the pairs as given in the example below:

Output

Key-value pair is: (Cycles, 3)
Key-value pair is: (Bikes, 6)
Key-value pair is: (Cars, 11)

The above example prints the key and its relevant values in the output. This example is useful to parse the elements and find the pairs in the output.

Find the Combination of Keys and Values Using For Loop in PHP

In addition to the above loop, you can also use the PHP for loop to find the combination of keys and its matching values. It requires counting the size of the array and store in a variable for iteration. This is required to iterate through the elements of an associative array. After that, you also have to return the array keys using the PHP array_keys() to find the keys using the loop. See the example learn the method:

Output

Key => Value pair is: (Cycles, 4)
Key => Value pair is: (Bikes, 9)
Key => Value pair is: (Cars, 13)

The above showing the same keys and values that you want to find from the given array variable.

How to Get Specific Value From an Associative Array by Key Using PHP

You can also find the specific value from the matching key of the associative array in PHP. For this, you also have to use the PHP if statement as given in the example below:

Output

The specific value for the key is: 6

The above example showing the value of the matching key or given key. It uses the equal operator (==) to find if the given key matches with elements of an associative array. If the given key matches with the element, it is the required value that you have to print in the output.

All the methods are given above use the loop to get the matching items of an array in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.