Basic Array Functions in PHP

June 15, 2020
PHP
array functions in php

In this tutorial, I’m going to show you the essential functions of working with an array in PHP. I’m going to post tutorials about collections, 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 a large number of variables like having 50 variables. Instead of declaring 50 of them, you can store these 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 service. To create the page, open your HTML code editor and paste the code below after the tag.

<!DOCTYPE html>
<html>
<head>
<title>Basic Array Functions in PHP</title>
</head>
<body>
    <?php
        $my_array=array(1,4,3,6,8,12,23,7,20,33,66);
    ?>
    Our Array: <?php print_r($my_array); ?> <br>
                //Determines the number of elements in array
    Number of Elements: <?php echo count($my_array); ?> <br>
                //Determines the maximum value in array
    Maximum Value: <?php echo max($my_array); ?> <br>
                //Determines the minimum value in array
    Minimum Value: <?php echo min($my_array); ?> <br>
                //Sorting array in ascending order
    Sorted(Ascending): <?php sort($my_array); print_r($my_array); ?> <br>
                //Sorting array in descending order
    Sorted(Descending): <?php rsort($my_array); print_r($my_array); ?> <br>
                //Joining array elements with a string
    Implode(-): <?php echo implode('-',$my_array); ?> <br>
    Implode(/): <?php echo implode('/',$my_array); ?> <br>
 
    <?php $name="N E O V I C"; ?>
                //Separates a string via specified string
    Explode: <?php print_r(explode(" ",$name)); ?> <br>
                //Returnns true if a value is found in array
    In array(20): <?php echo in_array(20,$my_array);?> <br>
    In array(4): <?php echo in_array(9,$my_array);?> <br>
</body>
</html>

Happy Coding!

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *