PHP Associative Array

Associative Array performs same function as that of Indexed Array but unlike Indexed Array which uses Numeric Index, Associative Array uses a String Index for referring to an element of array. In PHP, if you want to create an associative array, you are required to use the => operator.

Associative Array can be specified in following two different ways

  • With the use of array() construct
  • With the use of array operator[]

Specifying an associative array using the array() construct

Syntax:

$arrayName=array(key1 => value1,key2=> value2,....);

Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
echo "My Name is:".$myInfo["Name"]."and my age is:".myInfo["Age"];
?> 

This will produce following result

My Name is:Jimi and my age is:11

Specifying an associative array using array operator[]

Syntax

$arrayName=array();
$arrayName[key1]=value1;
$arrayName[key2]=value2;
.....

Example

<?php 
$myInfo=array();
$myInfo["Name"]="Jimi";
$myInfo["Class"]="Seventh";
$myInfo["Age"]=11;
echo "My Name is:".$myInfo["Name"]."and my class is:".myInfo["Class"];
?> 

This will produce following result:

My Name is:Jimi and my class is:Seventh

To count number of elements in an associative array

This can be done using count() function.

Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
echo count($myInfo);
?> 

This will produce following result

3

To display elements in an associative array using Foreach

This can be done using count() function.

Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
foreach($myInfo $key=>$value){
echo $key."is".$value;
echo "</br>";
?> 

This will produce following result

Name is Jimi
Class is seventh
Age is 11


 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.