tags:

views:

108

answers:

5

can you give me examples of using array() function ?

+5  A: 

There are plenty of examples in the manual:

http://php.net/manual/en/language.types.array.php

more specifically:

http://www.php.net/manual/en/function.array.php

karim79
The one page documentation is a must read if you are developing in PHP. It doesn't take long.
Marcus Adams
A: 
$arr = array(1, 2, 3, 4, 5);

To loop over each element in the array:

foreach($arr as $val) {
     print "$var\n";
}
synic
+2  A: 
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';

$someotherarray = array(1 => 'foo', 2 => 'bar');

var_dump($somearray);
echo $someotherarray[2];
Ignacio Vazquez-Abrams
When assigning a value to an array using the format `$array[] = `, specifically with no key, the array is automatically created if it doesn't already exist. Therefore, creating the array beforehand using `array()` is optional.
Marcus Adams
@Marcus: I personally prefer to not hope for PHP to do the right thing with uninitialized variables.
Ignacio Vazquez-Abrams
+1  A: 
$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);
Brant
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']);
Marcus Adams