PHP Array Introduction
From w3cyberlearnings
Contents |
PHP Array Introduction
Array is very important for data storage. There are two types of array: a normal array and an associative array. Please see the example on how to create an array in PHP.
Example 1
Create array use array() function.
<?php $actor = array( 'Greta Garbo', 'Andy Garcia', 'Ava Gardner', 'Lucy Johnson' ); ?>
Example 2
Create an array manually with an index.
<?php $actor[0] = 'Greta Garbo'; $actor[1] = 'Andy Garcia'; $actor[3] = 'Ava Gardner'; $actor[4] = 'Lucy Johnson'; ?>
Example 3
Create an array manullay without index.
<?php $actor[] = 'Greta Garbo'; $actor[] = 'Andy Garcia'; $actor[] = 'Ava Gardner'; $actor[] = 'Lucy Johnson'; ?>
Example 4
Create an associative array manually assign key and value pair ($actor[key]=value).
<?php $actor['id100'] = 'Greta Garbo'; $actor['id200'] = 'Andy Garcia'; $actor['id300'] = 'Ava Gardner'; $actor['id400'] = 'Lucy Johnson'; ?>
Example 5
- Create an associative array all at once.
<?php $actor = array( 'id100' => 'Greta Garbo', 'id200' => 'Andy Garcia', 'id300' => 'Ava Gardner', 'id400' => 'Lucy Johnson' ); ?>
Example 6: Create Multiple arrays
- Complex array
<?php $actor = array( 'id100' => array('name' => 'Greta Garbo', 'age' => 38), 'id200' => array('name' => 'Andy Garcia', 'age' => 31), 'id300' => array('name' => 'Ava Gardner', 'age' => 32), 'id400' => array('name' => 'Lucy Johnson', 'age' => 28) ); ?>
Example 7: Create Multiple arrays
- Create multiple array manually.
<?php $actor['id100'] = array('name' => 'Greta Garbo', 'age' => 38); $actor['id200'] = array('name' => 'Andy Garcia', 'age' => 31); $actor['id300'] = array('name' => 'Ava Gardner', 'age' => 32); $actor['id400'] = array('name' => 'Lucy Johnson', 'age' => 28); ?>
Related Links
--PHP Array Introduction-- PHP Access Array-- PHP Array Convert to Object-- PHP Array Convert to JSON-- PHP Array Convert to Class-- PHP Array Convert to String--