Web Programming TutorialsPHP Array Operations

PHP Array Operations

We learned to create arrays in PHP, today we will learn the operations that are carried on arrays using various built-in functions.

The built-in functions make it easier to manipulate arrays. So let us see some of the array manipulation functions below: To demonstrate the functions practically let us create a new folder array_operation in htdocs folder in xampp folder. Now open a new notepad++ document and save it as index.php in the newly created array_operation folder. To run and view the output, open a chrome browser and write localhost/array_operation in its address bar.

  1. count():
    • The count() function returns the number of elements in a given array.
    • Syntax :
    • count(array_name,mode_of_count);
    • The count() function has 2 parameters:
      1. array_name: array_name is the name of the array whose elements are to be counted.
      2. mode_of_count: This parameter is optional. There are 2 modes, 0 and 1. If mode_of_count parameter is given as 0, it will do a normal count even in a multidimensional array i.e. it will count only the main elements in the array. If mode_of_count is given as 1 then the function will count all the elements present in the array. When mode_of_count is given as 1, it is also called as revised count.
    • The count() function is frequently used to calculate the length of array when it is displayed or worked on in for loops.
  2. array_sum():
    • The array_sum() function returns the sum of all the values in a given array.
    • Syntax:
    • array_sum(array_name);
    • The array_sum() function has a single parameter array_name.
    • This is a mandatory parameter.
    • The function array_sum() gives the sum of all the elements present in the array.
    • Practical demonstration of functions count() and array_sum():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      
      	//demonstration of count function.
      	echo "1) count():<br>";
      	$games=array("Snake & Ladder","Ludo","Cricket","Hokey");
      	$len=count($games);
      	echo "<strong>Number of elements in array games = $len</strong><br>";
      	for($i=0;$i<$len;$i++)
      	{
      		echo "<strong>".$games[$i]."</strong><br>";
      	}
      	
      	//demonstration of count function.
      	echo "<br>2) array_sum():<br>";
      	$mks=array(78,56,89,65,90);
      	$sum=array_sum($mks);
      	echo "<strong>Sum of array elements = $sum</strong><br>";
      ?>
      </body>
      </html>
      
    • In the above code, we have declared an array $games with names of some games.
    • To count the number of elements in this array we used the count() function.
    • This is mostly used to display all the elements in array using loops.
    • So we had stored the output of count() function in variable $len and used it to form a condition in the for loop used.
    • To demonstrate the array_sum() function we have created an array $mks containing marks out of 100 in it.
    • Sum of all the marks in the array $mks is obtained by passing the array name $mks as a parameter in the function array_sum().
    • The output is shown below:
    • count_array_sum_output
      fig 1

  3. array_reverse():
    • The array_reverse() function is used to return an array in the reverse order.
    • Syntax:
    • array_reverse(array,preserve);
    • The array_reverse() function has 2 parameters of which the second one is optional.
    • Parameter array is the name of the array to be reversed.
    • Parameter preserve specifies if the array should preserve the keys of the array or not. If its value is true, it preserves its keys and if its value is false it does not preserve its keys.
  4. shuffle():
    • The shuffle() function randomizes the order of elements in the array.
    • After shuffling it assigns new keys to the elements in the array. It returns true on success and false on failure.
    • Syntax:
    • shuffle(array);
    • It takes the name of the array to be shuffled as a parameter.
    • Practical demonstration of functions array_reverse() and shuffle():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      	//demonstration of array_reverse function.
      	echo "3) array_reverse():<br>";
      	$cities=array("D"=>"Delhi","M"=>"Mumbai","N"=>"Nagpur");
      	print_r($cities);
      	echo "<br><strong>Reversed array:</strong> <br>";
      	$rev=array_reverse($cities);
      	print_r($rev);
      	echo("<br><br>");
      	
      	//demonstration of shuffle function.
      	echo "<br>4) shuffle():<br>";
      	shuffle($cities);
      	print_r($cities);
      ?>
      </body>
      </html>
      
    • In the above code we have created an array named $cities.
    • The original array is printed using print_r() fumction. The function print_r() is specially designed to print array formats.
    • The order of array $cities is reversed using aray_reverse() function and then printed using print_r() function.
    • Next we used the shuffle() function to randomize the elements in the array. The shuffling is done in the given array itself ad it is printed using print_r() function.
    • This function may be useful in computerized lucky draws.
    • The output is shown below:
    • array_reverse_shuffle_output
      fig 2

  5. sort():
    • The sort() function sorts the indexed array in ascending order.
    • Syntax:
    • sort(array,sorting_type);
    • The function sort() has two parameters of which the second is optional.
    • The parameter array is the name of the array to be sorted.
    • The parameter sorting_type specifies how to compare the array elements.
    • The sorting_type sorts the arrays depending on the following types:
      • 0 = SORT_REGULAR ->Sort items normally. This is the default sorting type.
      • 1 = SORT_NUMERIC ->Sort items numerically.
      • 2 = SORT_STRING -> Compare items as strings.
      • 3 = SORT_LOCALE_STRING -> Compare items as strings, based on current locale.
      • 4 = SORT_NATURAL -> Compare items as strings using natural ordering.
  6. rsort():
    • The rsort() function is used to sort an array in descending order.
    • It returns true on success and false on failure.
    • Syntax:
    • rsort(array, sorting_type);
    • The rsort() function takes the array name of the array to be sorted as the parameter.
    • The second parameter sorting_type is optional and has following values:
      • 0 = SORT_REGULAR ->Sort items normally. This is the default sorting type.
      • 1 = SORT_NUMERIC ->Sort items numerically.
      • 2 = SORT_STRING -> Compare items as strings.
      • 3 = SORT_LOCALE_STRING -> Compare items as strings, based on current locale.
      • 4 = SORT_NATURAL -> Compare items as strings using natural ordering.
    • Practical demonstration of functions sort() and rsort():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      	//demonstration of sort function.
      	echo "5) sort(): -> ascending order<br>";
      	$nos=array(90,56,45,89,70);
      	echo "Array nos before sorting:<br>";
      	foreach($nos as $n)
      		echo "<strong> $n &nbsp;&nbsp;</strong>";
      	echo "<br>";
      	echo "Array nos after sorting:<br>";
      	sort($nos);
      	foreach($nos as $n)
      		echo "<strong> $n &nbsp;&nbsp;</strong>";
      	echo "<br><br>";
      	
      	//demonstration of rsort function.
      	echo "6) rsort(): -> descending order<br>";
      	$nos1=array(10,90,20,56,45,30,70);
      	echo "Array nos1 before sorting:<br>";
      	foreach($nos1 as $n)
      		echo "<strong> $n &nbsp;&nbsp;</strong>";
      	echo "<br>";
      	echo "Array nos1 after sorting:<br>";
      	sort($nos1);
      	foreach($nos1 as $n)
      		echo "<strong> $n &nbsp;&nbsp;</strong>";
      	
      ?>
      </body>
      </html>
      
    • In the above code we have created a array named $nos.
    • This array is to be sorted in ascending order, hence the function sort() is used to sort it.
    • First the original array elements are displayed using foreach loop and then the array elements after sorting are displayed using foreach loop.
    • Next another array is created to demonstrate rsort() function. It sorts the array in descending order.
    • Here also the original array is displayed first and then the array sorted in descending order is displayed.
    • The output is shown below:
    • sort_rsort_output
      fig 3

  7. current():
    • The current() function returns the value of a current element in an array.
    • There is an internal pointer in an array which points to every element in an array. By default it always points to the first element i.e. the zeroth element of the array.
    • The current() function does not move the internal array.
    • It returns false if the array is empty.
    • Syntax:
    • current(array);
    • It takes the array whose current element value is to be known as the parameter.
  8. end():
    • The end() function moves the internal pointer to the last element of the array and returns the last element value of the array.
    • Syntax:
    • end(array);
    • It takes the array as the parameter whose last element value is to be known.
  9. next();
    • The next() function moves the internal pointer to the next element and returns its value.
    • Syntax:
    • next(array);
    • It takes the array as the parameter whose next element value is to be known.
  10. prev():
    • The prev() function moves the internal pointer to the previous element and returns its value.
    • Syntax:
    • prev(array);
    • It takes the array as the parameter whose previous element value is to be known.
  11. reset():
    • The reset() function moves the internal pointer to the first element of the array and returns it value.
    • Syntax:
    • reset(array);
    • It takes the array as the parameter whose internal pointer is to be set at the first element.
  12. each():
    • The each() function returns the current element key and value from the array and moves the internal pointer forward.
    • It returns 4 values. First the key 1 and the value pointed by the internal pointer currently and then the index 0 and the key of the value pointed.
    • Syntax:
    • each(array);
    • It takes the array as the parameter.
    • Practical demonstration of functions current(), end(), next(), prev(),reset() and each():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      	//demonstration of current function.
      	$players=array("Shilpa","Monica","Shruti","Pranav","Rakesh");
      	echo "Array elements are: ";
      	foreach($players as $p)
      		echo $p."&nbsp;&nbsp;";
          
      	echo "<br><br>7)reset():".reset($players)."<br>";
      	echo "8)next():".next($players)."<br>";
      	echo "9)end():".end($players)."<br>";
      	echo "10)prev():".prev($players)."<br>";
      	echo "11)current():".current($players)."<br>";
      	echo "<br>12)each():<br>";
      	print_r(each($players));
      	
      ?>
      </body>
      </html>
      
    • In the above code we have created an array named $players.
    • The values of the array elements based on the position of internal pointer can be obtained using the following array functions:
      1. reset(): it is used to point the internal pointer to the first element of the array $players and return its value. It returns the first player name i.e. Shilpa.
      2. next():it is used to point the internal pointer to the next element of the array pointed presently and return its value. It returns the value Monica which is next to Shilpa.
      3. end():it is used to point the internal pointer to the last element of the array $players and return its value. It returns the value Rakesh which is last element of the array.
      4. prev():it is used to point the internal pointer to the previous element to the current position where it is pointing presently and return its value. It returns the value Pranav which lies previous to Rakesh in the array.
      5. current():it returns the value Pranav itself which is pointed presently by the internal pointer of the array.
      6. each(): it returns the key-value pair where the internal pointer points currently and moves the pointer forward. It returns the value Pranav for the index 1 and returns its key value 3 for the index 0.
    • The output is shown below:
    • current_reset_end_next_prev_each_output
      fig 4

  13. array_unique():
    • The array_unique() function is used to remove duplicate values from an aray.
    • If there are more than one similar values in a given array then, the array_unique() function keeps the first occurance of the duplicate values and removes the rest of the values.
    • It keeps the key of the first occurrence of the value.
    • Syntax:
    • array_unique(array);
    • It takes the array whose ambiguous elements are to be removed.
  14. array_merge():
    • The array_merge() function is used to merge one or more arrays into one.
    • Syntax:
    • array_merge(array1, array2, array3,….);
    • If two or more arrays passed to the array_merge() function have same keys, then the last key value overrides the first key value.
    • For example:
    • $prod=array(“s”=>“School Bag”,”b”=>”Books”,”w”=>”Water Bag”,”p”=>”Pencil box”);
      $price=array(“r”=>”10”,”b”=>”60”,”d”=>”90”,”p”=>”30”);
      print_r(array_merge($prod,$price));
      
      output = Array([s]=>School Bag,[b]=>60,[w]=>Water Bag,[p]=>30)
      
    • If we pass only one array to the array_merge() function and the keys are integers, then the function will return the array with new keys starting from 0,1 etc.
    • For example:
    •  $prod=array(5=>”Washing Machine”,6=>”Refrigerator”);
      Print_r(array_merge($prod));
      
      Output = Array([0]=> Washing Machine, [1]=>Refrigerator)
      
    • Practical demonstration of functions array_unique() and array_merge():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      	
      	//demonstration of array_unique function.
      	echo "13) array_unique():<br>";
      	$no=array(10,56,20,10,45,30,45);
      	echo "original array:<br>";
      	foreach($no as $m)
      		echo "<strong>".$m."&nbsp;&nbsp;</strong>";
      	$no1=array_unique($no);
      	echo "<br>unique array:<br>";
      	foreach($no1 as $m)
      		echo "<strong>".$m."&nbsp;&nbsp;</strong>";
      		
      	//demonstration of array_merge function.
      	echo "<br><br>14) array_merge():<br>";
      	$fruits=array("A"=>"Apple","M"=>"Mango","O"=>"Orange");
      	$flowers=array("R"=>"Rose","M"=>"Mogra","H"=>"Hibiscus");
      	echo "original fruits array:<br>";
      	foreach($fruits as $f)
      		echo "<strong>".$f."&nbsp;&nbsp;</strong>";
      	echo "<br>original flowers array:<br>";
      	foreach($flowers as $f)
      		echo "<strong>".$f."&nbsp;&nbsp;</strong>";
      	$res=array_merge($fruits,$flowers);
      	echo "<br>resultant array:<br>";
      	foreach($res as $f)
      		echo "<strong>".$f."&nbsp;&nbsp;</strong>";
      ?>
      </body>
      </html>
      
    • In the above code we have created an array $no which contains some numbers. Some numbers are duplicate.
    • The duplicate nos. are removed using array_unique() function.
    • Next we have created two arrays $fruits and $flowers.
    • These array are merged together using array_merge() function. While merging the second array value overrides the same key value in the first array.
    • The output is shown below:
    • array_unique_array_merge_output
      fig 5

  15. array_pop():
    • The array_pop() function deletes the last element from the array.
    • Syntax:
    • array_pop(array);
    • It takes array as a parameter whose last element is to be deleted.
    • It returns the last value from the array otherwise it returns NULL if the array is empty.
  16. array_push():
    • The array_push() function adds one or more values at the end of the array.
    • Syntax:
    • array_push(array,value1,value2,….);
    • Here, the parameter array is the one where we want to add some more values.
    • The value 1, value 2 etc are the values that can be added to the array.
    • We can add as many values we want at the end of the array.
    • While adding even though out array has string keys, the added values will have the numeric keys.
    • Practical demonstration of functions array_pop() and array_push():
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP ARRAY OPERATIONS</title>
      </head>
      <body>
      <?php
      	//demonstration of array_pop function.
      	echo "15) array_pop():<br>";
      	$fruits=array("A"=>"Apple","M"=>"Mango","O"=>"Orange");
      	echo "Original fruits array<br>";
      	foreach($fruits as $g)
      		echo "<strong>".$g."&nbsp;&nbsp;</strong>";
      	array_pop($fruits);
      	echo "<br>Changed fruits array ('Orange' deleted)<br>";
      	foreach($fruits as $g)
      		echo "<strong>".$g."&nbsp;&nbsp;</strong>";
      		
      	//demonstration of array_push function.
      	echo "<br><br>16) array_push():<br>";
      	$fruits1=array("A"=>"Apple","M"=>"Mango","O"=>"Orange");
      	echo "Original fruits1 array<br>";
      	foreach($fruits1 as $g)
      		echo "<strong>".$g."&nbsp;&nbsp;</strong>";
      	array_push($fruits1,"Guava","Papaya","Banana");
      	echo "<br>Changed fruits array (3 values added)<br>";
      	foreach($fruits1 as $g)
      		echo "<strong>".$g."&nbsp;&nbsp;</strong>";
      	echo "<br>Array repesentation:<br>";
      	print_r($fruits1);
      ?>
      </body>
      </html>
      
    • In the above code we have created an array named $fruits.
    • This array contains 3 elements of which the last one is deleted using array_pop() function.
    • Next we have created an $fruits1 array and used array_push() function to add some more elements at the end of the array.
    • The changed $fruits array shows that the 3 elements have been added to the array.
    • An array representation is shown at the end which shows that even if the keys of the array are strings, the newly added elements get the numeric keys.
    • The output is shown below:
    • array_pop_array_push
      fig 6

Thus we finished learning some of the important array functions to perform different operations on arrays.

Previous articlePHP Superglobals
Next articlePHP Arrays

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -