pTutorial

New way to learn PHP

PHP 5 Associative Array

Associative array

Sometimes you need to access elements in an array by name. An Associative array is indexed with strings.

Creating an associative array

$detail = array
(
name=>"john",//first method
roll_no=>38,
marks=>99,
"work"=>"student"
);
$det[name] = "john";//second method
$det[marks] = 95;

Creating and accessing an associative arrays example

<?php

$detail = array 
( 
'name'=>"john",//first method
'roll_no'=>38,
'marks'=>99,
'work'=>"student"
);
echo $detail['name']."
"; echo $detail['roll_no']."
"; echo $detail['work']."
"; $det['name'] = "john";//second method $det['marks'] = 95; echo $det['name']."
"; ?>

Access key and value

Access key and value using foreach loop

<?php

$name=array
(
"Audi"=>"R8",
"Bmw"=>" BMW Z4 M Coupe",
"SKODA"=>"Fabia"
);
echo "Key"."--------". "Value
"; foreach($name as $key=>$key_value) { echo $key ."--------". $key_value; echo "
"; } ?>

Length of an associative arrays

Count () function are used to find the length of an array, It's return number of element in an array.

Example of length of an array

<?php

$student=array('a'=>"John",'b'=>"Smith','c'=>"Brawn");
foreach( $student as $value )
{
echo "Name of student: $value 
"; } echo "number of element =". count($student); ?>

Multidimensional Arrays

Multidimensional arrays will be explained in the PHP Next section


QUOTES OF THE DAY

Well-begun is half done.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER