Tuesday, June 19, 2012

PHP Arrays Tutorials

PHP Arrays Tutorial and PHP Array Examples

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

PHP Array Syntax: Create an Array
language-construct array() is used to create an array in PHP. See example below

array( [key =>] value
  , …
key: key may be an integer or string
value: A value can be of any PHP type

$arr = array(“foo” => “bar”, 12 => true);
echo $arr["foo"]; this will print bar
echo $arr[12]; this will print 1

if you provide the brackets with no key specified, then the maximum of the existing integer indices +1 is taken as key. see below

$arr = array(5 => 1, 12 => 2); This will create an array with 2 elements
$arr[] = 56;     new key will be maximum key + 1 i.e $arr[13] = 56
$arr["x"] = 42;  This adds a new element to the array with key “x”

array(5 => 43, 32, 56, “b” => 12); This array is the same as following.
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);

Handling arrays from html form inputs to php scripts
Following example will show we can use an array from html form inputs.

HTML form with array
<input type=”checkbox” name=”selected_ids[]” value=”1?>
<input type=”checkbox” name=”selected_ids[]” value=”2?>
<input type=”checkbox” name=”selected_ids[]” value=”3?>
<input type=”checkbox” name=”selected_ids[]” value=”11?>
<input type=”checkbox” name=”selected_ids[]” value=”12?>
<input type=”checkbox” name=”selected_ids[]” value=”13?>

When we submit above form, it will generate $_POST['selected_ids'][] array to the form handling php script. This array holds all selected checkbox values from above html form. foreach() construct can be used to extract values from the array. Following code example will show how we can extract those values from the returning array.

foreach ($_POST['selected_ids'] as $key => $value) {
    echo “Key: $key; Value: $value<br>”;
for example if 1,2 and 12 is selected from the above html form then above code will print
Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12

No comments:

Post a Comment

There was an error in this gadget