November 24, 2026
How do you create an array in PHP? Give an example.
Arrays are used to store more than one values or you can say that arrays are use to store multiple values in a single variable. Arrays are very important data structure for any programming language. Suppose you have a list of items such as vegetables name, week days or a list of a company’s employee. For maintaining these lists you can create arrays. In PHP array's key can be made of a string it is not possible in some other languages.
Creating An Array
You can create an array in PHP in multiple ways. You can create array with Array keywords, and second method is you can create array with square brackets. Array creation examples are mentioned below:
Code
<?php
$myArray = [10];
$myArray1[] = "0";
?>
In above mentioned example explained how you can create an array with two different ways. In above mentioned example both statements create array which can store values. Sometimes it happens that you do not have information about list items in advanced and you want to create an array which add new elements at the time list items gets increased. For this situation you can create array as mentioned below:
Code
<?php
$myArray = [];
$myArray1[] = 0;
?>
Assigning values to an array
You can also assign values to an array at the time of creating it. Example is mentioned below:
Code
<?php
$myArray = ["Tomato", "Potato", "Carrot"];
$myArray1[] = "Mango";
$myArray1[] = "Guava";
$myArray1[] = "Orange";
?>
Accessing an array element
Suppose you want to print $myArray (in above mentioned example) array's all elements on your browser. So you have to write your array name and it's index value for accessing particular element's value. We are trying to do the same with below mentioned example please have a look.
Code
<?php
echo "First element of myArray array: " . $myArray[0] . "
";
echo "Second element of myArray array: " . $myArray[1] . "
";
echo "Third element of myArray array: " . $myArray[2] . "
";
?>
In above mentioned example you can see that array index value start with 0 it means you can find first array element value at 0 index. And you can find last array element at n-1 position of n number of array elements.
If you want to reassign a value to any array element then you can easily do that with below mentioned example:
Code
$myArray[1] = "Onion";
In above mentioned example now 'Onion' replace $myArray[1] value.
FAQ
1. What is a multidimensional array in PHP?
A multidimensional array is an array that contains one or more arrays as its elements. It is useful for organizing related information in multiple levels.
2. What are the different types of arrays in PHP?
PHP supports three commonly described array types: indexed arrays, associative arrays and multidimensional arrays.
3. What is an indexed array in PHP?
An indexed array stores values with numeric indexes, starting from zero by default.