Tags
Asked 2 years ago
9 Jun 2021
Views 187
david

david posted

how to Loop and store key value from associative array in php ?

how to Loop and store key value from associative array in PHP ?
Rasi

Rasi
answered Apr 26 '23 00:00

In PHP, you can loop through an associative array using a foreach loop and store the key-value pairs in separate variables or arrays. Here's an example:


//

 Define an associative array
$myArray = array("name" => "John", "age" => 30, "location" => "New York");

// Loop through the array and store the key-value pairs in separate variables
foreach ($myArray as $key => $value) {
  echo $key . ': ' . $value . '<br>';
}

In this example, we define an associative array $myArray. We use a foreach loop to loop through the array, and on each iteration, we store the key in the variable $key and the value in the variable $value. We then output the key-value pairs with a line break (<br>).

Output:



name: John
age: 30
location: New York

If you want to store the key-value pairs in separate arrays, you can declare two separate arrays and use the loop to push the key and value into the respective arrays. Here's an example:


/

/ Define an associative array
$myArray = array("name" => "John", "age" => 30, "location" => "New York");

// Declare two empty arrays
$keys = array();
$values = array();

// Loop through the array and store the keys and values in separate arrays
foreach ($myArray as $key => $value) {
  array_push($keys, $key);
  array_push($values, $value);
}

// Output the keys and values arrays
print_r($keys);
print_r($values);

In this example, we define an associative array $myArray. We declare two empty arrays $keys and $values. We use a foreach loop to loop through the array, and on each iteration, we push the key into the $keys array and the value into the $values array using the array_push() function. We then output the $keys and $values arrays using the print_r() function.

Output:


Array
(
    [0] => name
    [1] => age
    [2] => location
)
Array
(
    [0] => John
    [1] => 30
    [2] => New York
)
Post Answer