Learn How To Use Associative Array With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

Associative arrays are arrays that use named keys that you assign to them.

Associative_Arrays

There are two ways to create an associative arrays: 

1.First way to create an associate arrays:

$Bike = array("Bike-1"=>"35kmpl", "Bike-2"=>"40kmpl", "Bike-3"=>"42kmpl");

2.Second way to create an associate arrays:
$age['Bike-1'] = "35kmpl";
$age['Bike-2'] = "40kmpl";
$age['Bike-3'] = "42kmpl";

Example(1)
<?php
$Bike = array("Bike-1"=>"35kmpl", "Bike-2"=>"40kmpl", "Bike-3"=>"42kmpl");
echo " Model  Bike-1   Mileage " .$Bike['Bike-1'] ;
?>

You Can also Use Loop For an Associative Arrays:
Print all the values of an associative arrays through the foreach loop.


Example(2)
<?php
$Bike = array("Bike-1"=>"35kmpl", "Bike-2"=>"40kmpl", "Bike-3"=>"42kmpl");
foreach($Bike as $x => $x_value) {
    echo "<h3> Model -> Key=" . $x . ",Mileage -> Value=" . $x_value. "</h3>";
}
?>

Complete Code of  an Associative Arrays:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Associative Arrays</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>PHP Associative Arrays
        </h1>
    </div>
    <br>
    <h2>1.Creating Associative Arrays Without Loop</h2>
    <div class="well">
        <?php
        $Bike = array("Bike-1"=>"35kmpl", "Bike-2"=>"40kmpl", "Bike-3"=>"42kmpl");
        echo "<h3> Model  Bike-1   Mileage " .$Bike['Bike-1']."</h3>";
        ?>
    </div>
    <br>
    <h2>2.Creating Associative Arrays With Loop</h2>
    <div class="well">
        <?php
        $Bike = array("Bike-1"=>"35kmpl", "Bike-2"=>"40kmpl", "Bike-3"=>"42kmpl");
        foreach($Bike as $x => $x_value) {
            echo "<h3> Model -> Key=" . $x . ",Mileage -> Value=" . $x_value. "</h3>";
        }
        ?>
    </div>
</div>
</body>
</html>

Related Post