php

foreach loop php

<?php
    $fruits = ["apple", "banana", "orange"];
    foreach($fruits as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be 0, 1, 2 and $value apple, banana, orange
    }

    $fruit = [
        "name" => "apple",
        "qty"  => 50,
        "type" => "seasonal"
    ];
    foreach($fruit as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be name, qty, type and $value apple, 50 and seasonal
    }

    $fruits = [
        [
            "name" => "apple",
            "qty"  => 10,
            "type" => "seasonal"
        ],
        [
            "name" => "banana",
            "qty"  => 20,
            "type" => "seasonal"
        ]
    ];
    foreach($fruits as $key => $value) {
        echo $value["name"];
    }
?>
Was this helpful?