CS174
Chris Pollett
Sep 23, 2020
$a = array("hi", 1, 2); //for PHP >= 5.4 you can also use the syntax: $a = ["hi", 1, 2];
$b = ["hi", [1,2], 2]; $c = ["a" => "c"];
echo $a[0]." ".$c['a'];
foreach($arr as $var){echo $var;} foreach($assoc_arr as $key => $value){echo "Key $key Value $value";}
list($first, $second, ) = $arr; //$first will be $arr[0], $second will be $arr[1].
$arr = [0=> 1, 1=>2, 2=>3];
$arr = ["joe"=> 5, "mary" =>6];
$keys = array_keys($arr) and $values = array_values($arr);
$barr[1] = 5; // creates array $barr if doesn't exist
$list=[2,4,6,8]; unset($list[2]); // $list is now [0=>2,1=>4,3=>8]
$str="this is a string"; $words = explode(" ", $str); /*make an array of tokens of items between consecutive spaces. So words is the array ["this", "is", "a", "string"]. */ $str2 = implode(" ", $words); //undoes the explode.
current($arr)
can be used to return a pointer to the current element in an array $arr. The next($arr)
function can be used to advance this pointer and get its value:
$cities = ["San Jose", "San Diego"]; echo current($cities); // prints San Jose $another = next($cities); // $another is now San Diego;
each
, prev
, end
, and reset
to facilitate moving through array.
each
is similar to next
except after advancing the current pointer, it returns the old pointer as a two element array consisting of a key/value pair.
function nameOfFunction([parameter_list]){ /* function definition */}
function inc($i){return ++$i;}
function helloWorld() { ?> <h1>Hello World</h1> <?php }
$b = inc($a); // leaves the value of $a unchanged
$b = inc(&$a); //here the value of $a is changed (one is added to it).
$bob = 5; function test() { $bob = 6; echo $bob; //echo's 6 } test(); echo $bob; //echo's 5
$bob = 5; function test() { global $bob; # if did not do bob would be NULL echo $bob; } test();PHP also supports static local variables. These preserve states between function calls:
function addone() { static $count =0; echo $count++; }