Upload
silvester-newman
View
244
Download
1
Tags:
Embed Size (px)
Citation preview
Array & ForeachArray & Foreachอาร์�เร์ย์�และคำ�าสั่ �งวนล�ปอาร์�เร์ย์�และคำ�าสั่ �งวนล�ป
ContentContent
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 indexAssociative arrays - Arrays with named keysMultidimensional arrays - Arrays containing one or more arrays
Syntax
Syntax for indexed arrays:
Syntax for associative arrays:
array(value1,value2,value3,etc.);
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.";?>
Syntax
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
<?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 ) )
<?php$cars=array("Volvo","BMW","Toyota");$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; }?>
For()
Loop through and print all the values of an indexed array:
<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; }?>
Foreach()
Loop through and print all the values of an associative array:
Array Functions
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
Q & A