PHP array – Common Usage

You will use "print_r" and "foreach" many times during programming at the time of using array.


<?php
$arr3 = array('a', 'b', 'c', 'd');
echo '<pre>';
print_r($arr2);
echo '</pre>';
?>

print_r() will print whole array with key=>value pair in human readable format.

Delete every item, but not array


foreach ($arr3 as $key=>$value) {
unset($arr3[$key]);
}

foreach is specifically made for array. It provides an easy way to traverse an array.

List and array


<php
list ($var1, $var2) = array (1, 2); // $var1=1 and $var2=2
echo "$var1 : $var2";
$sql1 = "SELECT name, age from .......... WHERE id=1";
$res1 = mysql_query($sql1);
list ($name, $age) = mysql_fetch_assoc($res1);
echo "Name:$name";
echo "Age:$age";
?>

Next:
Prev: