PHP Associative Arrays

0 0
Read Time:43 Second

PHP Associative Arrays

Syntax:

Syntax for associative arrays:

array(key=>value,key=>value,key=>value,....)

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

There are two ways to create an associative array:

$age = array("Gaurav"=>"35", "FallenBlood"=>"37", "BroFar"=>"43");

or the key and value can be assigned manually:

$age['Gaurav'] = "35";
$age['FallenBlood'] = "37";
$age['BroFar'] = "43";

The named keys can then be used in a script:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is ".$age['Peter']." years old.";
?>

Loop Through an Associative Array:

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
  echo "Key=".$x.", Value=".$x_value;
  echo "<br />";
}
?>
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment