Sunday, December 29, 2024
Google search engine
HomeLanguagesIterate associative array using foreach loop in PHP

Iterate associative array using foreach loop in PHP

Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays in the foreach loop. Both arrays can combine into a single array using a foreach loop.

Array: Arrays in PHP is a type of data structure that allows to storing multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed by using their index or key.

Example:

Input : $sides = array('Up', 'Down', 'Left', 'Right')
        $directions = array('North', 'South', 'West', 'East')

Output :
Up => North
Down => South
Left => West
Right => East

Example 1: This example uses foreach loop to display the elements of associative array.




<?php
  
// Declare an associative array
$aso_arr = array(
    "Up"=>"North"
    "Down"=>"South"
    "Left"=>"West"
    "Right"=>"East"
);
  
// Use foreach loop to traverse each
// elements of array and display its
// key and value 
foreach($aso_arr as $side=>$direc) {
    echo $side . " => " . $direc . "\n"
}
  
?>


Output:

Up => North
Down => South
Left => West
Right => East

Example 2: This example uses array to display its index with value.




<?php
  
// Declare an array
$sides = array("Up", "Down", "Left", "Right");
  
// Use foreach loop to display the
// elements of array
foreach($sides as $index => $value) {
    echo "sides[" . $index . "] => " . $value . " \n";
}
  
?>


Output:

sides[0] => Up 
sides[1] => Down 
sides[2] => Left 
sides[3] => Right

Note: Every entry of the indexed array is similar to an associative array in which key is the index number.
For example:

$sides = array("00"=>"Up", "01"=>"Down", "02"=>"Left", "03"=>"Right");
$directions = array("00"=>"North", "01"=>"South", "02"=>"West", "03"=>"East");

Since the index are common in all indexed arrays so it can use these indexes to access the value in other arrays.

Example 3:




<?php 
  
// Declare and initialize array
$sides = array("Up", "Down", "Left", "Right");
$directions = array("North", "South", "West", "East");
  
// Use foreach loop to display array elements
foreach( $sides as $index => $side ) {
    echo $side . " => " . $directions[$index] . " \n";
}
  
?>


Output:

Up => North 
Down => South 
Left => West 
Right => East

RELATED ARTICLES

Most Popular

Recent Comments