Preloader

PHP Array Functions

PHP Tutorials
codevigyaan php

PHP array functions make it easy for programmers to manipulate arrays. The functions enable programmers to insert, delete, sort, search, and manipulate array values. Since arrays are used in almost all PHP projects, programmers can save time and write high-quality code by learning array functions.

count()

The count function returns the total number of elements in an array. Programmers use the function to control loops.

Example

<?php
$fruits = ["Apple", "Banana", "Mango"];
echo count($fruits);
?>

Output
3

array_push()

The array_push function appends one or more values to the end of an array.

Example

<?php
array_push($fruits, "Orange", "Grapes");
?>

array_pop()

The array_pop function deletes the last element of an array.

Example

<?php
array_pop($fruits);
?>

array_shift()

The array_shift function deletes the first element of an array. After deletion, PHP reindexes the array.

Example

<?php
array_shift($fruits);
?>

array_unshift()

The array_unshift function appends one or more elements to the beginning of an array.

Example

<?php
array_unshift($fruits, "Pineapple");
?>

in_array()

The in_array function searches for a value in an array. The function returns true or false.

Example

<?php
if (in_array("Apple", $fruits)) {
    echo "Apple found";
}
?>

array_merge()

The array_merge function merges two or more arrays into a single array.

Example

<?php
$moreFruits = ["Kiwi", "Papaya"];
$allFruits = array_merge($fruits, $moreFruits);
?>

sort()

The sort function sorts array values in ascending order.

Example

<?php
sort($fruits);
?>

rsort()

The rsort function sorts array values in descending order.

Example

<?php
rsort($fruits);
?>

array_keys()

The array_keys function returns all keys from an array.

Example

<?php
$keys = array_keys($fruits);
?>

array_values()

The array_values function returns all values from an array and resets indexes.

Example

<?php
$values = array_values($fruits);
?>

Summary

PHP array functions make it easier for programmers to handle large amounts of data. Instead of writing complicated logic, programmers use array functions to insert, delete, search, and sort values in an array. This makes programming easier and more understandable.

In real-life programming, programmers use array functions when handling form data, database query results, or user data. Array functions also eliminate errors because PHP automatically does most of the work. Therefore, learning array functions is time-saving and improves the quality of code.

PHP Array Types
PHP Loops in Depth
PHP Control Structures

You may also like...

Leave a Reply

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