PHP Associative Arrays - Code

PHP Numeric Arrays Previous Next PHP Multidimensional Arrays


In PHP Associative Array, each ID key is associated with a value.

when storing data about specific named values, a numerical array is not always the best way to do it.

With associative arrays we can use the values as keys and assign values to them.

The next example uses an array to assign prices to different computer parts. This can be achieved in two ways.

Method 1: $price = array("Monitor" =>2200, "Keyboard" =>1400, "Mouse " =>520);

Method 2:

The above array can also be declared as follows:

$price['Monitor'] = "2200";

$price['Mouse'] = "520";

$price['keyboard'] = "1400";

Filename: php / associative-arrays1.php


Code
<?php  
// associative array 1
$price = array("Monitor" =>2200, "Keyboard" =>1400, "Mouse " =>520);

foreach($prices as $price => $price_value){
echo $price.", Value = ".$price_value." 
"; } ?>

Running Step.


Type Url - https://localhost/php/associative-arrays1.php

Filename: php / associative-arrays2.php


Code
<?php  
// associative array 2

$price['Monitor'] = "2200";
$price['Mouse'] = "520";
$price['keyboard'] = "1400";

echo "The price of a Mouse is RS ".$price['Mouse'];
?>

Running Step.


Type Url - https://localhost/php/associative-arrays2.php


Tags: PHP Associative Arrays PHP Code Programming Language


Was this helpful ?

Related Code