Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

PHP Associative Array

Associative array is one of the most useful Arrays. In this article we will see the advantages of use Associative Array in PHP.

Array is a special type of variable that store more than one data at a time. So it is very necessary for every language. As for that reasons we can use Array in PHP. Generally PHP support three types of array.

  • Numerical Array
  • Multidimensional Array
  • Associative Array

Normally we know that the array index start from 0 value that denote numerical value. But Associative array is such type of array that supports index value with string data. For that reasons we can take more advantages when we are creating different types of programming. This Array has different advantages like.

Advantages of Associative Array:

  • We set index value as String format $sname ["subrata"] = "Srimani";
  • This index value is totally our choice.
  • For that reason when we set database programming or others programming data are set with easily remember process.
  • Habitually when we use Session or Cookies programming then that system support associative array concept. Like $_SESSION['view']=2;
  • It is very easily to remember the index data.
  • We can use it just real array.
  • It is use like list, dictionary, collection, stack, queue and probably other also.
  • We can create different types of sorting process using Associative Array.
  • It is also support to changing key and value for different reasons.
  • We can also merging two associative arrays with PHP function.

Following sample code shows the Associative Array.

PHP Array Syntax

PHP language-construct array() is used to create an array. See example below:

Listing 1: Sample showing array syntax

array( [key =>] value
   …
  )

Generally it is also two parts one is key and the other is value.

  • key: This key may be an integer or string format.
  • Value: A value can be of any PHP type

Listing 2: Sample showing key-value pair in array syntax

$arr = array(“cei” => “maa”, 10 => true);
echo $arr["cei"]; this will print maa
echo $arr[10]; this will print 1

If we provide the brackets without any key specified, then the maximum of the existing integer value is taken as key with value indices +1.

Process to create Associative Array:

Associative array creation is very easy process. Because we already know that this array also support string index value which is totally user defined. So when we use this associative array then we have to remember that the associative array indexing is totally based on our choice.

The following example shows that creation of Associative Array.

Listing 3: Sample showing creation of Associative Array

<?php

$course = array ("C++"=>"Rs.1400", "Java"=>"Rs.1600","PHP"=>"Rs.2400","Netwoking"=>"Rs.3000");

?>

Listing 4: Sample showing Example of Associative Array

<?php
$sname = array();
$sname["Subrata"] = "Srimani";
$sname["Sukanta"] = "Sreemany";
$sname["Ayantika"] = "Roy";
$sname["Sushmita"] = "Das";
foreach ($sname as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
print "First name = " . $first_name . " Second name = " . $surname . "<BR>";
}
?> 

Output:

Key = Subrata Value = Srimani
First name = Subrata Second name = Srimani
Key = Sukanta Value = Sreemany
First name = Sukanta Second name = Sreemany
Key = Ayantika Value = Roy
First name = Ayantika Second name = Roy
Key = Sushmita Value = Das
First name = Sushmita Second name = Das

Process to create Different Sorting using Associative Array:

Specially Sorting are two types, one is called ascending order and others is called descending. Ascending means sorting data A-Z and descending order means Z-A order.

Here we can develop sorting the array using value and using keys as these two parts are very necessary for associative array.

  • asort(): This is Special type of sorting that sort the data using value. It’s can’t return anything
  • ksort(): This is Special type of sorting that sort the data using key. It’s can’t return anything.

Following is a sample code:

Listing 5: Sample code showing different sorting procedure

<?php
//Different sorting procedure using Associative Array
$stu_marks = array ("Sushmita"=>"535", "Payal"=>"670", "Ayantika"=>"605","Rahul"=>"170","Olivia"=>"570");

print("Before asort: <br>");

foreach ($stu_marks as $marks=>$no) {
print("There are $no ${marks}s.<br>");
}
asort($stu_marks);

print("After asort: <br>");

foreach ($stu_marks as $marks=>$no) {
print("There are $no ${marks}s.<br>");
}

print("Before ksort: <br>");

foreach ($stu_marks as $marks=>$no) {
print("There are $no ${marks}s.<br>");
}

ksort($stu_marks);

print("After ksort: <br>");

foreach ($stu_marks as $marks=>$no) {
print("There are $no ${marks}s.<br>");
}
?> 

Output: There are

Before asort:
There are 535 Sushmitas.
There are 670 Payals.
There are 605 Ayantikas.
There are 170 Rahuls.
There are 570 Olivias.
After asort:
There are 170 Rahuls.
There are 535 Sushmitas.
There are 570 Olivias.
There are 605 Ayantikas.
There are 670 Payals.
Before ksort:
There are 170 Rahuls.
There are 535 Sushmitas.
There are 570 Olivias.
There are 605 Ayantikas.
There are 670 Payals.
After ksort:
There are 605 Ayantikas.
There are 570 Olivias.
There are 670 Payals.
There are 170 Rahuls.
There are 535 Sushmitas.

Process to use arrays with HTML inputs to php scripts:

Following example will show we can use an array from html form inputs.

HTML form with array

<input type=”checkbox” name=”cei[]” value=”1″>
<input type=”checkbox” name=”cei[]” value=”2″>
<input type=”checkbox” name=”cei[]” value=”3″>
<input type=”checkbox” name=”cei[]” value=”11″>
<input type=”checkbox” name=”cei[]” value=”12″>
<input type=”checkbox” name=”cei[]” value=”13″>

If we submit this form like $_POST['cei'][] array to the form handling php script. Then array holds all selected checkbox values from this html form.

Process to Removing Array Elements from Associative Array:

  • unset() function is used to remove an elements from the array
  • unset($memory['RAM']);
  • array_shift() and array_pop() functions are also very flexibility to remove the elements from the array when we are using numerically indexed arrays.

Process to Swapping Keys and Values from Associative Array:

The array_flip() function is very popular function specially in Associative array, because in this array key and value in this two types are also used simultaneously. So, it may occur to interchange key and value for different reasons. This job is easily controlled by this function.

The following example is support to the job.

Listing 6: Sample code showing swapping

$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
$states = array_flip($city);
// $states = array(
//  'WestBengal'=> string 'kolkata',
//  'Maharastra'=> string 'Mumbai'  ,
//  'Bihar'=> string 'Patna'
// );

Process to Merging Arrays from Associative Array:

The array_merge()function is one of the most important function for merging two array. Because it is one of the most important features that we generally used to merge data from one array to another array. As it was very complicated process in previous but in PHP this function easily help us to merge two arrays.

Listing 7: Sample code showing merging

$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
$state = array (
  'Islamabad' => 'Pakistan',
  'Delhi'   => 'India',
  'Dhaka'   => 'Bangladesh'
);
$capitals = array_merge($city, $state);

Process to Editing Array Values from Associative Array:

The array_map()function is used to callback to every array element if we found any types of error like capitalization errors. Then the following procedure is used to solving this process.

Listing 8: Sample code showing editing

function capital($element)
{
  $element = strtolower($element);
  return ucwords($element);
}
//This strtolower() function is used to convert to upper data to lower character.
$city = array(
  'kolkata' => 'weSTBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
$capitals = array_map("capital", $city);

Process to Randomizing Array Order from Associative Array:

The shuffle() function is the another function to sort data with randomizing order process. The following example is use to show process.

Listing 9: Sample code showing randomizing
$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
shuffle($city);

array_rand() function is also used to randomly select value from the Associative array data.

Process to check existing key and value in Associative Array:

The in_array() function is use to check array value is exists or not this is following example show that.

Listing 10: Sample code showing checking key and value

$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
if(in_array("WestBengal", $city))
{
  echo "Present";
} 
else 
{
  echo "Does not Present!";
}

array_key_exists()function also use to check array key element is exists or not this is following example show that.

$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
if (array_key_exists("Mumbai", $city))
{
  echo "Key is presents!";
} 
else 
{
  echo "Key does not presents!";
}

Process to search data from Associative Array:

The array_search() function is used for searching data from associative array block. The following example shows that.

Listing 10: Sample code showing searching data

$city = array(
  'kolkata' => 'WestBengal',
  'Mumbai'  => 'Maharastra',
  'Patna' => 'Bihar'
);
$state = array_search('kolkata', $city);
// $state = 'WestBengal'

Conclusion

So, from the above discussion and examples, we can easily conclude that the concept of the Associative array is very powerful for our modern programming technology like PHP. The various examples show us the practical usage of different functions and methods. Hope you got good understanding of the concept and able to implement it in your applications.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login