170 likes | 257 Views
Array & Foreach อาร์เรย์และคำสั่งวนลูป. Content. 1. Definition and Usage 2. Syntax 3. print_r () Statement 4. For and Foreach 5. Array Functions. Definition and Usage. The array() function is used to create an array. In PHP, there are three types of arrays:
E N D
Array & Foreachอาร์เรย์และคำสั่งวนลูป
Content 1. Definition and Usage 2. Syntax 3. print_r() Statement 4. For and Foreach 5. Array Functions
Definition and Usage • The array() function is used to create an array. • In PHP, there are three types of arrays: • Indexed arrays- Arrays with numeric index • Associative arrays- Arrays with named keys • Multidimensional arrays- Arrays containing one or more arrays
Syntax Syntax for indexed arrays: array(value1,value2,value3,etc.); Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.);
Syntax <?php$cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; // การใช้เครื่องหมาย . เป็นการเชื่อมประโยคเข้าด้วยกัน?>
Syntax <?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old.";?>
Syntax <?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old.";?>
print_r Statement PHP 4, PHP 5 print_r — Prints human-readable information about a variable Source: http://php.net/manual/en/function.print-r.php
print_r Statement <?php $b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z')); $results = print_r($b); // $results now contains output from print_r ?> Array ( [m] => monkey [foo] => bar [x] => Array ( [0] => x [1] => y [2] => z ) )
For() Loop through and print all the values of an indexed array: <?php$cars=array("Volvo","BMW","Toyota");$arrlength=count($cars);for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; }?>
Foreach() Loop through and print all the values of an associative array: <?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; }?>
Array Functions • count($ar) - How many elements in an array • is_array($ar) - Returns TRUE if a variable is an array • sort($ar) - Sorts the array values (loses key) • ksort($ar) - Sorts the array by key • asort($ar) - Sorts array by value, keeping key association • shuffle($ar) - Shuffles the array into random order
Array and String $txt = “This is a book !”; $ar = explode(' ', $txt); print_r($ar); Array ( [0] => This [1] => is [2] => a [3] => book! )
Summary • PHP arrays are a very powerful associative array as they can be indexed by integers like a list, or use keys to look values up like a hash map or dictionary • There are many options for sorting • We can use explode() to split a string into an array of strings