PHP Arrays

📘 PHP 👁 36 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Arrays in PHP are used to store multiple values in a single variable. They are one of the most important data structures in PHP and are widely used in web development and frameworks like Laravel.


1. What Is an Array?

An array is a collection of values stored under a single variable name. Each value is accessed using an index or a key.

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

2. Types of Arrays in PHP

PHP supports three main types of arrays:

  1. Indexed Arrays

  2. Associative Arrays

  3. Multidimensional Arrays


3. Indexed Arrays

Indexed arrays use numeric indexes starting from 0.

$fruits = ["Apple", "Banana", "Orange"]; echo $fruits[0]; // Apple

Using array() function:

$numbers = array(10, 20, 30);

4. Associative Arrays

Associative arrays use named keys.

$user = [ "name" => "John", "email" => "john@example.com", "age" => 25 ]; echo $user["email"];

5. Multidimensional Arrays

Arrays containing one or more arrays.

$students = [ ["name" => "Amit", "marks" => 80], ["name" => "Rahul", "marks" => 90] ]; echo $students[1]["name"]; // Rahul

6. Looping Through Arrays

Using foreach

foreach ($fruits as $fruit) { echo $fruit; }

Associative Array Loop

foreach ($user as $key => $value) { echo $key . ": " . $value; }

7. Common Array Functions

count()

count($fruits);

array_push()

array_push($fruits, "Mango");

array_pop()

array_pop($fruits);

array_merge()

array_merge($array1, $array2);

in_array()

in_array("Apple", $fruits);

8. Sorting Arrays

sort()

sort($fruits);

asort()

asort($user);

ksort()

ksort($user);

9. Array Destructuring (PHP 7.1+)

[$a, $b] = [10, 20];

10. Array Functions for Advanced Use

  • array_map()

  • array_filter()

  • array_reduce()

Example:

$numbers = [1, 2, 3, 4]; $even = array_filter($numbers, fn($n) => $n % 2 === 0);

Conclusion

Arrays are a core part of PHP programming, allowing you to manage collections of data efficiently. Mastering PHP arrays and their functions is essential for building dynamic applications and working effectively with Laravel and other PHP frameworks.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes