← Back to Chapters

PHP Arrays

? PHP Arrays

? Quick Overview

PHP arrays are used to store multiple values in a single variable. An array can hold a collection of values that can be accessed using indexes or keys.

? Interactive Playground

Visualizing array_push($fruits, value)

 

Array Count: 3

? Key Concepts

  • Indexed Arrays – Use numeric indexes starting from 0
  • Associative Arrays – Use custom keys (string or integer)

? Syntax & Theory

Arrays in PHP can be created using the array() function or short array syntax. They allow structured storage and easy manipulation of data.

? Indexed Arrays

? View Code Example
// Creating an indexed array and accessing the first element

? Associative Arrays

? View Code Example
// Associative array using custom string keys
35,"John"=>30,"Doe"=>25);
echo $age["Peter"];
?>

?️ Operations on Arrays

? View Code Example
// Adding elements and counting array size

? Multidimensional Arrays

? View Code Example
// Matrix-style multidimensional array

? Nested Arrays

? View Code Example
// Accessing nested associative array values
1,"name"=>"Laptop","price"=>1000),
array("id"=>2,"name"=>"Phone","price"=>500)
);
echo $products[0]["name"];
?>

? Array Functions

? View Code Example
// Extracting keys from an associative array
"Apple","b"=>"Banana");
$keys = array_keys($fruits);
print_r($keys);
?>

? Live Output / Explanation

The output depends on the accessed index or key. PHP retrieves values directly from arrays using their respective indexes or keys.

? Use Cases

  • Storing lists like products, users, or scores
  • Handling form data
  • Managing configuration settings
  • Working with databases and APIs

✅ Tips & Best Practices

  • Use associative arrays for meaningful key-value mapping
  • Check array indexes before accessing
  • Use built-in array functions for cleaner code

? Try It Yourself

  • Create an indexed array and loop through it
  • Create a student-grade associative array
  • Apply discounts using array manipulation
  • Practice nested array traversal