Functions of Arrays in PHP Made Easy – Predefined Array Functions

0
78
Functions of Arrays in PHP
Functions of Arrays in PHP

Another series of Arrays in PHP and here’s an article on Predefined Array Functions. Today we will learn various functions of arrays in PHP with Code Examples. Here we are talking about widely used PHP Array Functions like:- Count(), List(), is_array(), in_array(), array_pop(), array_values(), explode(), Shuffle(), r_sort().

Predefined Array Functions in PHP Made Easy

<?php

echo "<body bgcolor=#f0f9f9></body>";

$arr1=array("Macky","PHP","14");
$n=count($arr1); //Count() - Function to total number of Elements

echo "No of Elements : $n <br><br>";
list($name,$sub, $marks)=$arr1; 
//list() function: Assigning values to a list of variables of an array
echo "$name <br> $sub <br> $marks <br>";

//Checking whether passed variable is an array or not using: is_array()
$result = is_array($name);
if(($result==1)){
 echo "<br>Passed variable is an array <br>";
}
else{
 echo "<br>Passed Paramenter is a normal Variable<br>";
}
 
//Checking if a value exist in an array using: in_array()
$chk=in_array("Macky",$arr1);
echo $chk . "<br>"; //WIll return 1 if exist

Predefined Array Functions

//Making new array, and just printing it
$arr2=array(57,13,44,23,98);
echo "<pre>";
print_r(array_values($arr2));
echo "</pre>";

//Inserting Values to an array using: array_push()
array_push($arr2,56,41,44,77);
echo "<pre>";
print_r(array_values($arr2)); //Printing new array
echo "</pre>";



//Deleting the last element from an array using - array_pop()
$num=array_pop($arr2);
echo "$num has been removed from array";
$num=array_pop($arr2);
echo "<br>$num has been removed from array<br><br>";
echo "<pre>";
print_r(array_values($arr2)); //Printing new array
echo "</pre>";



//Sorting array in Ascending Order using: sort()
sort($arr2);
echo "<pre>";
print_r(array_values($arr2)); 
//Printing new array After Arranging in Ascending order
echo "</pre>";



//Sorting array in Descending Order using: rsort()
rsort($arr2);
echo "<pre>";
print_r(array_values($arr2)); //Printing new array After Arranging in 
Descending order using predefined rsort() php function
echo "</pre>";



//shuffle() function in PHP
shuffle($arr2);
echo "<pre>";
print_r(array_values($arr2)); 
//Printing new array After shuffling the array using PHP array function: shuffle()
echo "</pre>";



//using explode function of php arrays. The explode function splits the strng on
 the basis of any delimitter. Like space.

$str="My name is Macky.";
$str1=explode(' ',$str);
print_r(array_values($str1));
?>

 

I hope you liked this article and understood all basic Predefined Array functions of PHP. If you have any doubt, just comment below. If you need any other help, contact us. You can follow our PHP Programming Tutorials series here. Thank you for checking out.

LEAVE A REPLY

Please enter your comment!
Please enter your name here