How to Use Arrays in PHP

In programming, we represent our data in terms of variable. As variable holds single value of a particular data type. This is not enough when you want to represent more than one value of any variable and in such case you have to use array.

Take a look at this code -

<?php
$number=1;
?>

When you execute this php file on your web server you’re going see this output

1

Now when you work with arrays you get to work with multiple values in same variables. Take a look at this code :

<?php
$number=array('one','two', 'three','four','five','six','seven');
?>

After executing the above code you’ll see that it prints out -

one,two, three,four,five,six,seven

Numerical Arrays

In this type of array you can decide how many values you wish to keep in a variable. It starts from position 0 to the specified position in the bracket. For example $number[3] array is going to hold total four values in the variable.

<?php
$number[0]='one';
$number[1]='two';
$number[2]='three';
$number[3]='four';
echo $number[1];
?>

Associative Arrays

This type of array allows you to have key-value pair inside array. When you’re dealing with the relative values then associative arrays are useful.

<?php
$population["Karakura"]=20000;
$population["soul society"]=45000;
$population["hell"]=6000000;
echo $population["soul society"];
?>

As you can see from these two types of arrays that they can hold more values than variable. So if you’re going to write a program that deals with the multiple value of same type of variable then consider using variable. You can also use arrays when you wish to use key-pair type of values. Do remember that default position of numerical arrays start from position 0 and you have to keep that in mind when creating arrays of exact size.

Related Posts:

  1. PHP Loops