Arrays help you store many pieces of information in one place. They make it easy to organize and use data together.
Why arrays are essential in PHP
<?php // Creating an array $arrayName = array(value1, value2, value3); // Or using short syntax $arrayName = [value1, value2, value3]; // Accessing an element echo $arrayName[index]; // Associative array with keys $assocArray = ["key1" => "value1", "key2" => "value2"]; // Accessing by key echo $assocArray["key1"]; ?>
Arrays in PHP can hold different types of data together, like numbers and strings.
PHP arrays can be indexed by numbers or by custom keys (associative arrays).
<?php // Empty array $emptyArray = []; print_r($emptyArray); ?>
<?php // Array with one element $singleElementArray = ["apple"]; print_r($singleElementArray); ?>
<?php // Associative array with keys $user = ["name" => "Alice", "age" => 30]; echo $user["name"]; ?>
<?php // Numeric indexed array $numbers = [10, 20, 30]; echo $numbers[2]; ?>
This program shows how to create an array, add an item, and access an element by its position.
<?php // Create an array of fruits $fruits = ["apple", "banana", "cherry"]; // Print the original array echo "Original fruits array:\n"; print_r($fruits); // Add a new fruit $fruits[] = "date"; echo "\nAfter adding a new fruit:\n"; print_r($fruits); // Access and print the second fruit echo "\nThe second fruit is: " . $fruits[1] . "\n"; ?>
Time complexity for accessing an element by index or key is very fast (constant time).
Arrays use extra memory to store keys and values, so very large arrays can use more memory.
Common mistake: forgetting that PHP arrays start indexing at 0 for numeric keys.
Use arrays when you need to group related data and access it easily by position or key.
Arrays store many values together in one variable.
They can use numbers or keys to find data quickly.
Arrays make it easy to organize and work with groups of information.