can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0
.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);