PHP Array Cheat Sheet: A Quick Reference Guide

Post Thumbnail of PHP Array Cheat Sheet

Arrays are essential data structures in PHP that allow you to store and manipulate collections of data.

PHP provides various functions and methods for working with arrays, making it a versatile language for handling complex data structures.

In this PHP array cheat sheet, we'll provide a quick reference guide to the most common array operations and functions to help you efficiently work with arrays in PHP.

Creating Arrays

Create an Empty Array

$emptyArray = [];

Create an Indexed Array

$colors = ["Red", "Green", "Blue"];

Create an Associative Array

$person = [
    "first_name" => "John",
    "last_name" => "Doe",
    "age" => 30
];

Create a Multidimensional Array

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

Accessing Array Elements

Access by Index

$colors[0]; // Returns "Red"

Access by Key

$person["first_name"]; // Returns "John"

Modifying Arrays

Add an Element

$colors[] = "Yellow"; // Appends "Yellow" to the end of the array

Update an Element

$person["age"] = 35; // Updates the "age" key to 35

Remove an Element

unset($colors[1]); // Removes the element at index 1

Array Functions

Count the Number of Elements

$count = count($colors); // Returns the number of elements in $colors

Check if an Element Exists

$exists = in_array("Red", $colors); // Returns true if "Red" exists in $colors

Find the Keys of a Value

$keys = array_keys($person, "Doe"); // Returns ["last_name"]

Merge Two Arrays

$mergedArray = array_merge($array1, $array2); // Merges $array1 and $array2

Sort an Array

sort($numbers); // Sorts $numbers in ascending order

Reverse an Array

$reversedArray = array_reverse($numbers); // Reverses the order of elements in $numbers

Remove Duplicates from an Array

$uniqueArray = array_unique($numbers); // Removes duplicate values from $numbers

Extract a Slice of an Array

$slice = array_slice($numbers, 2, 3); // Extracts a slice starting from index 2 with a length of 3

Combine Two Arrays into an Associative Array

$combinedArray = array_combine($keys, $values); // Combines $keys and $values into an associative array

Iterating Through Arrays

Using foreach

foreach ($colors as $color) {
    echo $color . " ";
}

Using for

for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . " ";
}

Using while

$i = 0;
while ($i < count($colors)) {
    echo $colors[$i] . " ";
    $i++;
}

This cheat sheet covers the most common PHP array operations and functions to help you work with arrays effectively. Keep this reference handy as you explore more complex array manipulations and become proficient in PHP array handling.