Download presentation
Presentation is loading. Please wait.
Published bySilvester Newman Modified over 9 years ago
1
Array & Foreach อาร์เรย์และคำสั่งวนลูป
2
Content 1. Definition and Usage 2. Syntax 3. print_r() Statement 4. For and Foreach 5. Array Functions
3
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
4
Syntax Syntax for indexed arrays: Syntax for associative arrays: array(value1,value2,value3,etc.); array(key=>value,key=>value,key=>value,etc.);
5
Syntax
6
<?php $cars=array("Volvo","BMW","Toyota"); echo "I like ". $cars[0]. ", ". $cars[1]. " and ". $cars[2]. "."; // การใช้เครื่องหมาย. เป็นการเชื่อมประโยคเข้าด้วยกัน ?> Syntax
7
"35","Ben"=>"37","Joe"=>" 43"); echo "Peter is ". $age['Peter']. " years old."; ?> Syntax
8
"35","Ben"=>"37","Joe"=>" 43"); echo "Peter is ". $age['Peter']. " years old."; ?> Syntax
9
PHP 4, PHP 5 print_r — Prints human-readable information about a variable print_r Statement Source: http://php.net/manual/en/function.print-r.php
10
<?php $b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z')); $results = print_r($b); // $results now contains output from print_r ?> print_r Statement Array ( [m] => monkey [foo] => bar [x] => Array ( [0] => x [1] => y [2] => z ) )
11
"; } ?> For() Loop through and print all the values of an indexed array:
12
"35","Ben"=>"37","Joe"=>" 43"); foreach($age as $x=>$x_value) { echo "Key=". $x. ", Value=". $x_value; echo " "; } ?> Foreach() Loop through and print all the values of an associative array:
13
Array Functions
14
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
15
Array and String $txt = “This is a book !”; $ar = explode(' ', $txt); print_r($ar); Array ( [0] => This [1] => is [2] => a [3] => book! )
16
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
17
Q & A
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.