Post Pic

How to Create Array in PHP

What is an array? You have to understand what is it before start using it. An array is a variable which allows you to store multiple value within it!

What is an array? You have to understand what is it before start using it. An array is a variable which allows you to store multiple value within it! Here is an illustration. Have you ever saw a file cabinet usually found in offices, a cabinet where there’s a lot of drawers to store important files for easy searching and organizing? That is what array similar to.

In PHP, it is possible to store an array within an array. PHP has the flexibility to array handling! If using the above example to illustrate it, then it would be storing a file cabinet within a file cabinet. How’s that sound? Hmm … Unfortunately, it is impossible :)

Well, to start using an array, the first step is to create an array variable.

1
2
3
4
<?php
$color = array();
 
?>

When PHP read this code, it will assign this variable $color as an array. But it is empty. It still has no elements within it. Now we are going to place some highly confidential files into this cabinet.

1
2
3
4
<?php
$color = array("red", "blue", "yellow");
 
?>

Take a look at how those elements are stored within it. First, you have to use double quote for opening and closing of a string and then followed by a comma which tells PHP to seperate each element from the others.
How to identify those array?
When you assign values into array elements, PHP uniquely identify each and every elements with keys. It always start with 0. As with the code above, key[0] has the value of ‘red’, key[1] is ‘blue’ and the last one key[2] is ‘yellow’.

Thus, when you want to access an element of an array, you have to enter the array variable $color followed by the key number. Let say you want to print out those values stored inside. It can be done like this:

1
2
3
4
5
6
7
<?php
$color = array("red", "blue", "yellow");
echo $color[0];
echo $color[1];
echo $color[2];
 
?>

Array looping
If you had tons of elements stored within an array, it will takes you quite some time to type in one by one. Instead of typing it, you can use ‘foreach’ statement to loop all the value within an array.

1
2
3
4
5
6
7
<?php
$color = array("red", "blue", "yellow");
foreach($color as $key => $value) {
echo $key . " " . $value . "<br>";
}
 
?>

And the result will be

1
2
3
0 red
1 blue
2 yellow

Related posts:

  1. Create Professional Wordpress Themes With New Book   WordPress is an open-source blog engine released under...
  2. How to create an article in Joomla I will take you through a step by step process...

Recent Response

09.17.09

this is test …

Leave Comments

* Name, Email, Comment are Required

Categories

Song of the Day!!

Flash required

orionbipin2bipin1105074067