PHP Array
$_SERVER, print_r(), foreach(), associative(); count(),list(), extract()
Indexed array or Enumerative array
Associative array
<?php
$ar['a']=1;
$ar[]=2;// index will be 0
$ar[5]=3;
$ar[0]=4;//overwrite index 0
$ar['0']=5;//overwrite index 0
$ar['01']=6;
$ar[01]=7;
print_r($ar);//Array ( [a] => 1 [0] => 5 [5] => 3 [01] => 6 [1] => 7 )
var_dump($ar);/*
array (size=5)
'a' => int 1
0 => int 5
5 => int 3
'01' => int 6
1 => int 7
*/
?>
|
• Different ways to Create arrays
• Output arrays vprintf
• Test for an array
Foreach Example
Html File
<form action="login.php" method="post">
Your favourite browser:
<option>IE</option>
<select multiple name="browsers[]">
<option>Chrome</option>
<option>Mozilla</option>
<option>Safsari</option>
</form>
</select>
<input type="submit" value="Login">
PHP File
login.php
<?php
$favBrowsers=array(); $favBrowsers=$_POST['browsers']; foreach ($favBrowsers as $favBrowser){ echo $favBrowser; } ?>
echo "The capital of India is {$capitals['India']}.";//for complex array/object
array inbuilt function
• Add and remove array elements
array_sum(),array_push(),array_pop(),array_unshift(),array_shift(),array_pad($name,4,”hi”);
unset(value to be remove)
• Locate array elements
boolean is_array() ,boolean in_array(), boolean array_search(),
• Traverse arrays array_walk
current(),key(),next(),p rev(),reset(),end(), each(),array_values(),array_keys()
array_reverse(), shuffle(),
• Determine array size and element uniqueness
int sizeof(),int count(),compact(),array_unique()
array_rand();list(), extract(),
• Sort arrays
sorting: sort(),rsort(), asort(),arsort(), ksort(),krsort()
• Merge, slice, splice, and dissect arrays
array_merge(),array_combine() array_chunk(),array_slice(),array_splice()
Math function : array_sum(), round(),
$_SERVER, print_r(), foreach(), associative(); count(),list()
|
array_walk()
Example: array_walk(array,function)
function add10($value ) {
$value += 10 ;
echo $value . " " ;
}
$testgrades = array(87,88,98,74,56,94,67,98,49) ;
var_dump($testgrades);
echo "<br/><br/>";
array_walk($testgrades, 'add10');
//array(9) { [0]=> int(87) [1]=> int(88) [2]=> int(98) [3]=> int(74) [4]=> int(56) [5]=>
int(94) [6]=> int(67) [7]=> int(98) [8]=> int(49) }
//97 98 108 84 66 104 77 108 59
|