PHP Array Operations

0
2713

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 :
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • Practical demonstration of functions array_unique() and array_merge():
    • Write the following code in index.php file:
    • 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:
    • 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:
    • 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:
    • 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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here