3 Ways to Create Arrays in PHP

0
234
3 ways to Create Arrays in PHP

Let’s look at another article in our series of PHP programming for beginners. Here you will learn a number of ways by which you can create arrays in PHP. This is a very basic tutorial, but you must know the basics of arrays first. You can read our Arrays introduction article here. So after reading basics, lets get started:

//first method to Create Arrays in PHP

<?php

$car[]= “BMW”;
$car[]= “Maruti”;
$car[]= “Bugati”;

print_r($car);

In first method we simply store the value in array with empty square brackets like this: $my_array[]=”Store_value”;
This will store the value in the first empty location of array. The “print_r()” function in PHP is used to print all the values of an array on screen.

//Second Method of Creating an Array in PHP is

echo “<br>”;
$food[0]=”Chowmein”;
$food[1]=”Burger”;
$food[2]=”momos”;
print_r($food);

echo “<br><br>”;

Here in Second method, you give index values of array while storing values. Mind the fact that, index postion of an array always starts from 0 (and not from 1). So we simply store values like this, $my_array[index_value]=”Data_to_store”;

//Third way to Create Arrays in PHP using array keyword

$students= array(“Mukesh”,”Ravi”,”zaid”);

//let’s print it out using PHP ‘for loop’

for($i=0;$i<3;$i++)
echo $students[$i].”<BR>”;

?>

This is the most commonly used method to create arrays in PHP. You simply use the ‘array’ Keyword and store the values. You don’t have to give the Index values, it will automatically store them in order. For Example, $my_array=array(“Data1″,”Data2″,”Data3”);
Dont’ forget to separate each data using Commas.

 

Create Arrays in PHP
Output of Above Statements

We will be posting more tutorials on Arrays in PHP. So stay connected, follow our newsletter or join us on our Facebook page to get updates of upcoming articles. We hope you learnt all 3 ways to create arrays in PHP, in case you have any doubt in here you can comment down. We will love to solve your doubts. Thanks for showing up.

LEAVE A REPLY

Please enter your comment!
Please enter your name here