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,

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,


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 
Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question