Basic Array Functions in PHP

In this tutorial, I'm going to show you the basic functions in working with array in PHP. I'm going to post tutorials about arrays, so this tutorial is the starting line. An array is a data structure that stores one or more values into a single value. It is useful in defining large number of variables like having 50 variables. Instead of declaring 50 of them, you can store this 50 values into a single variable.

Creating our Functions

The first and last step is to create our page with our functions. I've also included in the comments the definition of each function. To create the page, open your HTML code editor and paste the code below after the tag.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Basic Array Functions in PHP</title>
  5. </head>
  6. <body>
  7.         <?php
  8.                 $my_array=array(1,4,3,6,8,12,23,7,20,33,66);
  9.         ?>
  10.         Our Array: <?php print_r($my_array); ?> <br>
  11.                                 //Determines the number of elements in array
  12.         Number of Elements: <?php echo count($my_array); ?> <br>
  13.                                 //Determines the maximum value in array
  14.         Maximum Value: <?php echo max($my_array); ?> <br>
  15.                                 //Determines the minimum value in array
  16.         Minimum Value: <?php echo min($my_array); ?> <br>
  17.                                 //Sorting array in ascending order
  18.         Sorted(Ascending): <?php sort($my_array); print_r($my_array); ?> <br>
  19.                                 //Sorting array in descending order
  20.         Sorted(Descending): <?php rsort($my_array); print_r($my_array); ?> <br>
  21.                                 //Joining array elements with a string
  22.         Implode(-): <?php echo implode('-',$my_array); ?> <br>
  23.         Implode(/): <?php echo implode('/',$my_array); ?> <br>
  24.        
  25.         <?php $name="N E O V I C"; ?>
  26.                                 //Separates a string via specified string
  27.         Explode: <?php print_r(explode(" ",$name)); ?> <br>
  28.                                 //Returnns true if a value is found in array
  29.         In array(20): <?php echo in_array(20,$my_array);?> <br>
  30.         In array(4): <?php echo in_array(9,$my_array);?> <br>
  31. </body>
  32. </html>

Add new comment