PHP - Usefull array functions

After looking at string functions, let's look at arrays.
You will find yourself using array very often. In this example we will see just a few of many useful array functions. I will explain these functions in code comments.

<?php
  // create an array
  $my_array = array(1, 2, 3, 4, 5, 7, 56, 745, 76, 4567, 345, 63456, 345, 6457, 45);
  echo "\nInitial array\n";
  // display array
  var_dump($my_array);
  // count elements in array
  $count = count($my_array);
  echo "\n\$my_array have " . $count . "elements\n";
  // sort array
  sort($my_array);
  echo "\nSorted array\n";
  // display array another way
  print_r($my_array);
  // reverse array
  $my_array = array_reverse($my_array);
  echo "\nReversed array\n";
  print_r($my_array);
  // random order of elements in array
  shuffle($my_array);
  echo "\nRandom order\n";
  print_r($my_array);
  // create another array
  $my_another_array = array(3, 4, 455, 677, 5676, 34745, 746, 4515, 456, 45, 300);
  // display array
  echo "\nAnother array\n";
  print_r($my_another_array);
  // sort array in reverse order (similar to sort it and then reverse it)
  rsort($my_another_array);
  echo "\nReverse sorted array\n";
  print_r($my_another_array);
  // difference between two arrays (returns elements in $my_array not contained in $my_another_array)
  $difference_array = array_diff($my_array, $my_another_array);
  // display array
  echo "\nDiference (elements in \$my_array not contained in \$my_another_array)\n";
  print_r($difference_array);
  // intersection - elements contained in both arrays
  $intersection_array = array_intersect($my_array, $my_another_array);
  echo "\nIntersection (elements contained in both arrays)\n";
  print_r($intersection_array);
  // merge array - all elements from both arrays
  $merged_array = array_merge($my_array, $my_another_array);
  echo "\nMerged array\n";
  print_r($merged_array);
  // remove duplicates from array
  $merged_array = array_unique($merged_array);
  echo "\nMerged array without duplicates\n";
  print_r($merged_array);
  // Check for value and get its index
  $element_index = array_search(76, $my_array);
  echo "value 76 in array \$my_array is element with index " . $element_index . "\n";
  // Just check if value exists in array
  if (in_array(76, $my_array))
    echo "value 76 is in the array\n";
  if ( ! in_array(1000, $my_array))
    echo "but value 1000 is not\n";
  echo "\n\nand many many more…"
?>

Related Marakana Courses

  • PHP and MySQL Bootcamp Training

Leave a Reply