PHP Programing Botturn

All About PHP, Tutorials, Scripts, Video Lessons, Forum, Downloads


TUTORIAL - Arrays and PHP example with checkbox

Posted by admin On April - 30-2009
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 an array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. As you may 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 an example

array ([key =>] value
...
)
key: key can be an integer or string
value: A value can be any PHP type

Examples
$ Arr = array ("foo" => "bar", 12 => true);
echo $ arr ["foo"]; this will print bar
echo $ arr [12], this will print a

If you provide the brackets with no key specified, then the maximum value of existing indexes is taken as a whole key. see below

$ Arr = array (5 => 1, 12 => 2); This will create an array with 2 elements
$ Arr [] = 56; new key will be maximum ie a key + $ arr [13] = 56
$ Arr ["x"] = 42;

This adds a new element into the array with the key "x"

array (5 => 43, 32, 56, "b" => 12); The Same This array is the following.
array (5 => 43, 6 => 32, 7 => 56, "b" => 12);

Following example will show that we can use an array of HTML form input.
Handling HTML form input arrays to PHP scripts

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 you submit the form above, will generate $ _POST ['selected_ids'] [] array to the form handling php script. This array holds all selected checkbox values ​​above HTML form. foreach () construct can be used to extract values ​​of the matrix. Following sample code will show how we can extract these values ​​from the return array.

foreach ($ _POST ['selected_ids'] as $ key => $ value) {
echo "Key: $ key, Value: $ value <br>";
}

for example, 1.2 and 12 are selected from the HTML form above then above code will print

Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12

Popularity: 17% [ ? ]

Related posts Brought to you by Yet Another Related Posts Plugin .

Leave a Reply