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.

Related :   Online tools for Software Developers from ExtendsClass

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 


Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )


1 thought on “How to create Arrays in PHP ?”

Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded