In this part, we are going to learn about arrays function in PHP. In PHP there are a lot of functions that work with arrays.
PHP arrays Functions
It can manipulate the data with the help of different built-in functions. Here we will look for some common arrays functions in PHP.
$numbers = array(4,5,12,14,15,29);
We can use the different functions in PHP to perform an action on these numbers. For example, we can count all the numbers stored in variable ‘$number’ by using ‘count’ function.
Here is the syntax:
<?php count($numbers); ?>
Similarly we can calculate maximum and minimum numbers by using max and min function.
<?php max($numbers); ?>
The function will show the maximum number from arrays.
<?php min($numbers); ?>
Similarly this function will show the maximum number from arrays.
We can also sort these numbers in a specific order by using sort and rsort functions.
Below is the example.
Sort: <?php sort($numbers);
Reverse sort: <?php rsort($numbers);
There is another important function ‘implode’ that turns an array into a string. The empty spaces in numbers can be replaced by any other number or special character. For example, if we want to use ‘*’ sign between two numbers instead of space, we can use implode function.
Here is the syntax.
<?php echo implode(“*”, $numbers); ?>
The output of the program is:
Here we replace the empty space of numbers (stored in $numbers) into a * sign. This is not an array anymore, implode functions has turned it into a string.
By using PHP arrays function we can also check whether something is in an array or not. The function can help us in checking whether a specific element is available in an array or not by returning true(1) or false(nothing).
The syntax for this function is given below.
5 in array?: <?php echo in_array(5, $numbers) ?><br>
10 in array?: <?php echo in_array(10, $numbers) ?>
Here is the output.
As 5 is present in arrays so it shows 1 as output. On the other hand, 10 is not present so it shows nothing as output.
There are many more functions for working with PHP arrays. If you want to learn more click here.