Associative Array syntax in php

Associative Array syntax in php

Array is one of the important term in web programming. If we want to send multiple data with just one variable then there is no alternative of using “ARRAY”. Array is really easy to understand and easy to implement in programming. Today we are going to learn how to implement Associative Array in php.  Lets get started.

In the first example, I am going to show how to define simple Associative array and in the second example we will see how to define a complex Associative array.

– Define Simple Associative Array:

//define simple array
$simple_array = array(
	"name" => "hkhan Khan",
	"postion" => "software Engineer",
	"group" => "web development"

//simple array output code
foreach($simple_array as $key=>$value) {
	echo "$key: ".$value;

– Define Complex Associative Array:

//define a complex array.
$complex_array = array(
	"name" => "hkhan Khan",
	"postion" => "software Engineer",
	"group" => "web development"
	"phone" => "11111111",
	"email" => "[email protected]",
	"website" => ""


//read a complex array
foreach($complex_array as $item) {
	echo $item['name'];
	echo $item['postion'];
	echo $item['group'];
	echo $item['phone'];
	echo $item['email'];
	echo $item['website'];

Some More PHP Array functions for further study.

– Convert a string in to an Array:

Most often in development time we need to convert a string in to an array. In that case our string must contain a delimiter by which we can separate each item in to an array. Like in this example we are using “comma” as our separator. PHP provide a great and very much useful function called explode that can easily convert a string into an array. Have a look at example:

$number_string = "267,266,91,286,85,287,87,78,84,89,90,277";
$convert_in_to_array =  explode(",",$number_string);

– Get Random element from an Array:

PHP provide a nice function called “array_rand” for getting random element from array lists. It takes 2 parameters as input. First one is a array and second one is amount of random value you want to get. In my example I’ve set 1 but you can set 2,3 any number. Have a look at example:

$array = array("bat","ball","cat","dog","man","woman","horse","mouse") ;
$rand_keys = array_rand($array, 1);
echo "Random Array Key: ".$rand_keys;
echo "Random Array Value: ".$array[$rand_keys];

This function returns you the index of element. If you set this index inside your array then you will get the value of random element. It’s simple and very easy to use.

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Total 0 Votes

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top