echo associative array php code example

Example 1: Associative array in php

<?php 
/* 
There are 3 Types of array in php  
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays

This is the second one - Associative arrays
*/

$age = array("Samy"=>"35", "Naveen"=>"37", "Amit"=>"43");
echo "Mr.Samy is " . $age['Samy'] . " years old.";

?>

Example 2: how to create associative array in php

<?php 
  /*
  there are three type of array
  	1 - Indexed array
  */
 	$a = array('a','b','c');
	$b = ['a','b','c'];
	/*
    2 - Associative array
    */
	$c = array(
    	'keyOne'=>'valueOne',
      	'keyTwo'=>'valueTwo'
    );
	$d = [
      'keyOne'=>'valueOne',
      'keyTwo'=>'valueTwo'
    ];
/*
    3 - Multidimensional  array
    */
	$c = array(
    	'keyOne'=>array('a','b','c'),
      	'keyTwo'=>array('a'=>'1','b'=>'2')
    );
	$d = [
      'keyOne'=>['a','b','c'],
      	'keyTwo'=>['a'=>'1','b'=>'2']
    ];
  ?>

Example 3: print asociative array php

//This is the declaration of an associative array.
$animals["firstindex"]="ape";
$animals["secondindex"]="dinosaur";
$animals["thirdindex"]="ahahah";
for(reset($animals);$element=key($animals);next($animals))
{print("$element is $animals[$element]");
}

//Can also be created by using an array function
$fourth=array("January"=>"first","February"=>"second","March"=>"third","April"=>"fourth");
foreach($fourth as $element=>$value)
print("$element is the $value month");

Example 4: associative array php

// Associative Array in PHP

/******** ARRAY TYPES  ************************************************
There are basically 03 Types of array in php  
1. Indexed arrays          => Arrays with a numeric index
2. Associative arrays      => Arrays with named keys
3. Multidimensional arrays => Arrays containing one or more arrays
***********************************************************************/

//EXAMPLE
//This is the second one - Associative arrays

$age = array("Peter"=>"35", "Naveen"=>"37", "Amit"=>"43");
echo "Mr.Samy is " . $age['Peter'] . " years old.";

Tags:

Php Example