Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

PHP Array Functions: The Ultimate Cheat Sheet

Posted on October 22, 2026







PHP Array Functions: The Ultimate Cheat Sheet – Complete Guide for Developers


PHP Array Functions: The Ultimate Cheat Sheet

Arrays are the backbone of data manipulation in PHP. Whether you’re building a simple script or a complex Laravel application, mastering PHP’s built‑in array functions can dramatically improve code readability, performance, and maintainability. This cheat sheet gathers the most commonly used functions, grouped by purpose, complete with short explanations and ready‑to‑copy code snippets.

Table of Contents

  1. Basic Array Functions
  2. Sorting Functions
  3. Searching & Retrieval
  4. Manipulation (Add / Remove)
  5. Filtering, Mapping & Reducing
  6. Merging & Splitting
  7. Iteration Helpers
  8. Best Practices & Common Pitfalls

Basic Array Functions

Creating & Counting

array() – The literal way to create an array.

$numbers = array(1, 2, 3, 4); // or $numbers = [1,2,3,4];

count() – Returns the number of elements.

echo count($numbers); // 4

Checking Types & Existence

is_array() – Verifies a variable is an array.

if (is_array($data)) { /* … */ }

array_key_exists() – Checks if a specific key is present.

if (array_key_exists('name', $user)) { /* … */ }

Extracting Keys & Values

array_keys() – Returns all keys.

$keys = array_keys($user);

array_values() – Returns all values, re‑indexing numerically.

$values = array_values($user);

Sorting Functions

Simple Sorting

sort() – Sorts an array in ascending order and re‑indexes numeric keys.

$arr = [3,1,4]; sort($arr); // [1,3,4]

rsort() – Same as sort() but descending.

Associative Sorting

asort() – Sorts by values while preserving key association.

$scores = ['Alice'=>90,'Bob'=>75]; asort($scores); // Alice => 90, Bob => 75

ksort() – Sorts by keys.

User‑Defined Sorting

usort() – Sorts using a custom callback.

usort($arr, function($a,$b){ return $a['age'] <=> $b['age']; });

Similar functions exist for keys: uksort(), uasort().

Searching & Retrieval

Value Search

in_array() – Checks if a value exists.

if (in_array('PHP', $languages)) { /* … */ }

array_search() – Returns the key of the first matching value.

$key = array_search('Bob', $names); // e.g., 2

Key Search

array_key_first() and array_key_last() – Retrieve the first or last key.

Finding Duplicates

array_unique() – Removes duplicate values.

$unique = array_unique([1,2,2,3]); // [1,2,3]

Manipulation (Add / Remove)

Adding Elements

array_push() – Append one or more values.

array_push($stack, 'new'); // $stack[] = 'new';

array_unshift() – Prepend values.

Removing Elements

array_pop() – Removes the last element.

$last = array_pop($stack);

array_shift() – Removes the first element.

Splicing & Slicing

array_slice() – Returns a portion of the array without altering the original.

$part = array_slice($arr, 2, 3); // from index 2, length 3

array_splice() – Removes/replaces a portion **and** modifies the original array.

array_splice($arr, 1, 2, ['a','b']); // replace 2 items starting at index 1

Filtering, Mapping & Reducing

Filtering

array_filter() – Returns elements that pass a callback test.

$evens = array_filter($numbers, fn($n) => $n % 2 === 0);

Mapping

array_map() – Applies a callback to each element.

$squared = array_map(fn($n) => $n*$n, $numbers);

Reducing

array_reduce() – Reduces the array to a single value.

$sum = array_reduce($numbers, fn($carry,$item)=>$carry+$item, 0);

Column Extraction

array_column() – Pulls out a single column from a multi‑dimensional array.

$emails = array_column($users, 'email');

Merging & Splitting

Merging

array_merge() – Combines arrays, re‑indexing numeric keys.

$all = array_merge($arr1, $arr2);

array_merge_recursive() – Merges recursively, turning duplicate keys into arrays.

Union Operator

+ – Preserves keys from the left array.

$union = $arr1 + $arr2; // $arr1 keys win

Chunking

array_chunk() – Splits an array into smaller pieces.

$chunks = array_chunk($numbers, 3); // [[1,2,3],[4,5,6],…]

Iteration Helpers

Walking

array_walk() – Applies a user function to each element (by reference).

Walking with Keys

array_walk_recursive() – Works on multi‑dimensional arrays.

Extracting Sub‑arrays

array_intersect() – Returns common values.

array_diff() – Returns values in the first array not present in others.

Best Practices & Common Pitfalls

  • Prefer native functions over loops. Functions like array_map and array_filter are implemented in C and are faster.
  • Beware of key re‑indexing. sort(), array_merge(), and array_values() reset numeric keys – use asort() or the union operator if you need to keep them.
  • Immutable vs mutable. Functions ending with “_slice” return a new array, while “_splice” modifies the original. Choose based on whether you want side‑effects.
  • Strict comparisons. Pass true as the third argument to in_array() for type‑safe checks.
  • Memory considerations. Large arrays combined with array_merge() can double memory usage. Use generators or yield for very large data sets.

Quick Reference Table

Category Function Description
Creation array() Creates a new array.
Count count() Returns element count.
Sorting sort(), asort(), ksort(), usort() Various sorting mechanisms.
Search in_array(), array_search() Find values or keys.
Add/Remove array_push(), array_pop(), array_shift()

Leave a Reply Cancel reply

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

Recent Posts

  • Pakistan Tours and Travels: A Guide to Choosing the Right Agency
  • PHP Array Functions: The Ultimate Cheat Sheet
  • Pakistan Tour Africa: Exploring Cricketing Ties with the Continent
  • Pakistan Tour Zimbabwe 2024 / 2025 / 2026: A Look at the Forthcoming Series
  • How to Sort Arrays in PHP

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check