Tutorials PHP PHP Arrays

PHP Arrays

Today you will learn about arrays. This will make it easier when you have multiple pieces of data that you need to process.

What is an array?

An array is like a list. It contains multiple pieces of data.

$array = array('Michelangelo','Leonardo','Donatello','Raphael');

How do you call an array?

You need to call it by the order in which it appears in the array.

$array = array('Michelangelo','Leonardo','Donatello','Raphael');

// outputs "My favourate turtle is Raphael"
echo 'My favourate turtle is '.$array[3];

Note: The order of arrays start at 0.

How do you loop through an array?

A special loop called foreach is designed to loop through arrays.

$array = array('Edmund','Lucy','Peter','Susan');

foreach ($array as $value) {
  echo 'My name is '.$value.'.<br/>';
}

I have a string in a certain format. Can I turn it into an array?

You can use the explode function to turn a string into an array. You need a common variable to separate your string. You could use a comma, period, space or anything else.

$string = 'red.violet.blue.green.yellow.orange';
$array = explode('.',$string);

Should I use arrays or a database?

If you don't want the trouble of maintaining a database, an array is easier to maintain and use. It's like buying a bicycle over a car. A car is more powerful but with great power comes great responsibility. If you buy a bicycle, you just pay for the bike and that's it. If you buy a car, you need to pay insurance, gas, maintenance, parking and a ton of other stuff. So for some people, owning a car is more trouble than it's worth.

This ends today's lesson. See you all next time.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.