Hosting Forum

Full Version: How to use associative array in php?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How to use associative array in php?
(04-25-2012 03:15 AM)phpdeveloperindia Wrote: [ -> ]How to use associative array in php?

An associative array also stores data in the same way but gives you more flexibility by letting you assign any name you want to your keys instead of using keys 0, 1, 2, 3, 4, and so on. This is helpful when you want to assign a certain value to your key.

For example, you want an array which display the height of school children in cm, your associative array function will look like this:

<?php
$height=array('Billy'=>90, 'Sam'=>95, 'Susie'=>92, Tamara=>89);
?>

To retrieve the value for each key you just have to type in:
echo $height ('Billy'); or
echo $height ('Sam'); and so on.

Hope this helps.
PHP is a scripting language mainly developed for web web development. A scripting language differs from compiled language in this respect that a compiled language like C,VB, etc.
In numeric array the index position is start from 0, the second is index position is 1 and so on. PHP supports associative array in which we can associate any kind of key with a value.
PHP is web programming language and server side scripting language. You can easily store data within array.

Example:

<html>
<body>

<?php
$city=array("Mark"=>"USA","Ben"=>"UK","John"=>"UAE");
echo "Mark from" . $city['Mark'] ;
?>

</body>
</html>
How to use associative arrays in PHP

In PHP we can use an “associative array” data type to store sets of (key, value) pairs. The functionality that these associative arrays provide is analogous to that of “hash” variables in Perl, and “Hashtables” in Java.
Define and initialize an array

We can initialize an array with some values using the syntax:
<?php
$capitals = array(
‘United Kingdom’ => ‘London’,
‘Peru’ => ‘Lima’,
‘France’ => ‘Paris’,
‘Portugal’ => ‘Lisboa'
);
?>
And since PHP 5.4, we can also use the syntax:
<?php
$capitals = [
‘United Kingdom’ => ‘London’,
‘Peru’ => ‘Lima’,
‘France’ => ‘Paris’,
‘Portugal’ => ‘Lisboa’,
];
?>
Reference URL's