Introduction
This is my first article in English. I have chosen for an article about array's in PHP because it makes the life of a php scripter easier.
Arrays are very useful in combination with mysql queries. Before starting with this tutorial please learn the basic about PHP like echo, variables and strings.
What is an Array?
An Array is a Variable with more than one string.
A variable have one string, see the example code:
$usernameta = 'edward';
$usernameb = 'john';
$agea = '20';
$ageb = '34';
echo $usernamea.'age is '.$agea.'<br />';
echo $usernameb.'age is '.$ageb.'<br />';
|
|
The same result with two arrays, one for the age and one for the username:
$username[0] = 'edward';
$username[1] = 'john';
$age[0] = '20';
$age[1] = '34';
echo $username[0].'age is '.$age[0].'<br />';
echo $username[1].'age is '.$age[1].'<br />';
|
|
The first number for a array is 0, unaltered as all other numbering in php.
The power of arrays
In combination with other functions from php you can make an automatic loop, this is not possible with normal variables. I show an example
with for
<?php
// how many users?
$show = 3;
$username[0] = 'edward';
$username[1] = 'john';
$username[2] = 'eddy';
$username[3] = 'Richard';
//I have leave the numbers, php know that automatic.
$age[] = '20';
$age[] = '34';
$age[] = '13';
$age[] = '19';
echo 'The first three users:<br />';
for ($count = 0; $count < $show; $count++)
{
echo $username[$count].' age is '.$age[$count].'<br />';
}
?>
|
|
The output is:
The first three users:
edward age is 20
john age is 34
eddy age is 13
|
|
An another method for filling an array with the same result is:
$username = array('edward','john','eddy','richard');
|
|
Not only a rising numbering is possible, you can use also give a name. For example:
$connect['server'] = 'localhost';
$connect['database'] = 'databasename';
$connect['user'] = 'root';
$connect['password'] = 'dontshowme';
|
|
in_array
There are a lot of functions for using with arrays, I show one function: in_array. With in_array you check of something present is in the array.
<?php
$username[0] = 'edward';
$username[1] = 'john';
$username[2] = 'eddy';
$username[3] = 'Richard';
$me = 'Richard';
if (in_array($me,$username)){
echo'Richard is present!';
}
?>
|
|
Mistakes in this article about my English please sent a private message

. Please feel free to add your questions and comments.