PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
An array in PHP is a type of data structure that allows you to store multiple values in a single variable. Here's how you can define an array:
An indexed array is a simple list of items in a specific order. The index of each item (starting from 0) is generated automatically. You can define an indexed array using the array()
function or the square bracket []
syntax.
$fruits = array("Apple", "Banana", "Cherry"); // or $fruits = ["Apple", "Banana", "Cherry"];
You can access elements of an indexed array like this:
echo $fruits[0]; // Outputs: Apple
Associative arrays are arrays that use named keys instead of numeric keys. You can create them using the array()
function or the []
syntax.
$ages = array("John" => 35, "Jane" => 32, "Bob" => 29); // or $ages = ["John" => 35, "Jane" => 32, "Bob" => 29];
In this example, the names are the keys, and the ages are the values. You can access the values by referring to the keys:
echo $ages["John"]; // Outputs: 35
A multidimensional array is an array containing one or more arrays. PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
$persons = array( "John" => array( "age" => 35, "email" => "john@example.com" ), "Jane" => array( "age" => 32, "email" => "jane@example.com" ) );
You can access elements of a multidimensional array like this:
echo $persons["John"]["age"]; // Outputs: 35
Remember that PHP arrays can contain different types of elements, so you can have an array that contains a combination of numbers, strings, and other arrays.
PHP Array Initialization:
$numbers = array(1, 2, 3, 4, 5);
PHP Indexed Array Declaration:
$fruits = array('Apple', 'Banana', 'Orange');
PHP Associative Array Declaration:
$person = array( 'name' => 'John', 'age' => 25, 'city' => 'New York' );
PHP Define Array with Values:
$colors = ['Red', 'Green', 'Blue'];
PHP Initialize Empty Array:
$emptyArray = array(); // OR $emptyArray = [];
PHP Dynamic Array Declaration:
$dynamicArray = array(); $dynamicArray[] = 'Element 1'; $dynamicArray[] = 'Element 2';
PHP Array Assignment:
$numbers[0] = 10; // Assigning a value to the first element of an indexed array $person['occupation'] = 'Engineer'; // Assigning a value to the 'occupation' key in an associative array