Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Arrays

Arrays store multiple values in a single variable. PHP supports indexed arrays, associative arrays, and multidimensional arrays.

Indexed, Associative & Multidimensional Arrays

Array Types
<?php
// Indexed array
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // apple
echo count($fruits); // 3

// Associative array
$person = [
    "name" => "Alice",
    "age"  => 30,
    "city" => "New York"
];
echo $person["name"]; // Alice

// Multidimensional array
$students = [
    ["name" => "Bob",   "grade" => "A"],
    ["name" => "Carol", "grade" => "B"],
    ["name" => "Dave",  "grade" => "C"],
];
echo $students[1]["name"];  // Carol
echo $students[1]["grade"]; // B
?>

Array Manipulation Functions

PHP provides a rich set of functions to add, remove, search, and transform arrays.

Array Functions - Add & Remove
<?php
$arr = [1, 2, 3];

array_push($arr, 4, 5);   // add to end   -> [1,2,3,4,5]
$last = array_pop($arr);  // remove end   -> $last=5, arr=[1,2,3,4]
array_unshift($arr, 0);   // add to start -> [0,1,2,3,4]
$first = array_shift($arr); // remove start -> $first=0, arr=[1,2,3,4]

// Merge arrays
$a = [1, 2];
$b = [3, 4];
$merged = array_merge($a, $b); // [1,2,3,4]

// Slice - extract portion
$slice = array_slice($merged, 1, 2); // [2,3]

// Unique values
$dup = [1, 2, 2, 3, 3, 4];
$unique = array_unique($dup); // [1,2,3,4]

// Search
echo in_array(3, $merged);          // 1 (true)
echo array_search(3, $merged);      // 2 (index)

// Keys and values
print_r(array_keys($person ?? []));
print_r(array_values($person ?? []));
?>

Sorting Arrays

PHP has multiple sort functions. sort() reindexes, while asort() preserves keys.

Sorting Arrays
<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];

sort($nums);   // ascending, reindex
print_r($nums); // [1,1,2,3,4,5,6,9]

rsort($nums);  // descending, reindex
print_r($nums); // [9,6,5,4,3,2,1,1]

// Associative sort (preserves keys)
$scores = ["Alice" => 85, "Bob" => 92, "Carol" => 78];
asort($scores);  // sort by value, keep keys
ksort($scores);  // sort by key alphabetically

// Custom sort
$people = [
    ["name" => "Bob",   "age" => 30],
    ["name" => "Alice", "age" => 25],
    ["name" => "Carol", "age" => 35],
];
usort($people, fn($a, $b) => $a["age"] - $b["age"]);
// Now sorted by age ascending
print_r($people);
?>

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.