About Lesson
Commonly Used PHP Array Functions
1. count():
Returns the count of elements in an array.
Example:
PHP
<?php
$fruits = array("Apple", "Banana", "Orange");
echo "Total fruits: " . count($fruits);
?>
Output: Total fruits: 3
2. array_push():
Adds one or more items to the end of an array.
Example:
PHP
<?php
$fruits = array("Apple", "Banana");
array_push($fruits, "Orange", "Mango");
print_r($fruits);
?>
Output: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
3. array_merge():
Combines two or more arrays into one.
Example:
PHP
<?php
$arr1 = array("red", "blue");
$arr2 = array("green", "yellow");
$merged = array_merge($arr1, $arr2);
print_r($merged);
?>
Output: Array ( [0] => red [1] => blue [2] => green [3] => yellow )
4. explode():
Splits a string into an array by using a delimiter.
Example:
PHP
<?php
$text = "Apple,Banana,Orange";
$fruits = explode(",", $text);
print_r($fruits);
?>
Output: Array ( [0] => Apple [1] => Banana [2] => Orange )
5. implode():
Opposite of explode(), this function combines array elements into a string.
Example:
PHP
<?php
$fruits = array("Apple", "Banana", "Orange");
$text = implode(" - ", $fruits);
echo $text;
?>
6. in_array():
Checks if a value exists in an array.
Example:
PHP
<?php
$fruits = array("Apple", "Banana", "Orange");
if (in_array("Banana", $fruits)) {
echo "Banana is available!";
}
?>
Output: Banana is available!
7. array_keys()
and array_values()
:
Get all keys or values from an array.
Example:
PHP
<?php
$student = array("name" => "John", "age" => 20, "grade" => "A");
print_r(array_keys($student)); // Output: Array ( [0] => name [1] => age [2] => grade )
print_r(array_values($student)); // Output: Array ( [0] => John [1] => 20 [2] => A )
?>