How to create Arrays in php ?

PHP provides simple function to create an array using “array()” API which creates an empty array. In this post lets try to create a simple array to begin and add an elements to this array and display those.

Creating an Array

$newArray = array();

Above this simple code, creates an Empty array, now we will try to add static elements to this array as,

$newArray[]=10;
echo "0th element is : $newArray[0] ";

The above code, initializes 0th element of this array to 10, and line below displays the same 0th element accessed using array index as $newArray[0]

Initializing an Array using for Loop

for ($i = 0; $i < 10; $i++) {
	$arrayUsingForLoop[] = $i;
}

foreach($arrayUsingForLoop as $arrayElement) 
	echo "$arrayElement <br>";

Above code creates an array “arrayUsingForLoop” and initializes the values to its elements using for loop. The code below “foreach” iterates over this newly created array and displays the elements of this array.

The output of this code will be like as below,

0
1
2
3
4
5
6
7
8
9 

Statically Initializing array elements

$categories = array("Linux", "Operating System", "Embedded", "Java");

Above code shows, how we can initialize a new array using static elements as we declare/define the array.

We have seen above, how we can iterate over an array and print its element using “foreach” method, below we will see how we can also print an index of the element.

Display Index of array in php

$categories = array("Linux", "Operating System", "Embedded", "Java");
foreach($categories as $index=>$category) 
	echo "$index: $category <br>";

The output of this code, will look like as below,

0: Linux
1: Operating System
2: Embedded
3: Java 
Follow Lynxbee

Leave a Reply / Ask Question