PHP Array Functions

PHP has many predefined array functions that can be used to read and manipulate arrays. The following is a list of the available functions.

count() Function

The count() function will count all the elements in an array and return the total number.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // getting the number of elements
  echo count($numbers); // 6
?>

max() Function

The max() function will find the highest value in an array if the only parameter provided is an array.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // getting highest element
  echo max($numbers); // 42
?>

min() Function

The min() function will find the lowest value in an array if the only parameter provided is an array.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // getting the lowest element
  echo min($numbers); // 4
?>

sort() Function

The sort() function will sort an array, in place, from lowest to highest.

NOTE

This is a destructive function and will change the array.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // sorting the array from lowest to highest
  print_r(sort($numbers));
?>

rsort() Function

The rsort() function will sort an array, in place, from highest to lowest.

NOTE

This is a destructive function and will change the array.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // sorting the array from highest to lowest
  print_r(rsort($numbers));
?>

implode() Function

The implode() function will join array elements with a string and return a string.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // join the array elements together to create a string
  echo implode(" * ", $numbers);
?>

explode() Function

The explode() function will split a string by a delimiter and return an array.

<?php
  $num_string = "8 * 23 * 15 * 42 * 16 * 4";
  
  // split the string into an array
  echo explode(" * ", $numbers);
?>

in_array() Function

The in_array() function will check if a value exists in an array. The function will return TRUE if the value is found, and FALSE if it is not.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // checking if 15 is in the array
  echo in_array(15, $numbers); // TRUE

  // checking if 19 is in the array
  echo in_array(19, $numbers); // FALSE
?>

array_push() Function

The array_push() function will add one or more elements to the end of an array. The function will return the new number of elements.

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // add 35 to the end of the array
  echo array_push($numbers, 35); // 7
?>

array_pop() Function

The array_push() function will remove the element at the end of an array. The function will return the value of the last element (the element that was removed).

<?php
  $numbers = [8, 23, 15, 42, 16, 4];
  
  // remove the last item in the array
  echo array_pop($numbers); // 4
?>