CS174
Chris Pollett
Mar 1, 2022
//if if ($a) print "hello"; if ($a) { print "hello"; print "there"; } if ($a) { $b = 1; echo $b; } else if ($b) { $b = 2; echo $b; } else { $c = 1; echo $c; } //switch case: switch($a) { case 5: echo "hello"; /* if $a matches the label (5 in this case) then execute the code after it; */ break; //if hit then jump out of switch case "a label made from a string": echo "weird labels still work"; break; default: echo "if all else fails do this"; }
for($a = 0; $a<10; $a++){echo "hello $a";}
while(!$var) { /*do something*/}
do {/*do something */} while (!$var);
<?php if ($the_world_is_round == true): ?> The world is not flat. <?php endif; ?>
$a = array("hi", 1, 2); //for PHP >= 5.4 you can also use the syntax: $a = ["hi", 1, 2]; //this is what modern PHP should use
$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).
function myadd($a = 1, $b = 2, $c =3) { echo ($a+$b+$c) . "\n"; } myadd(); //outputs 6 myadd(c: 4); // outputs 7 (PHP 8)
the quick brown foxbecomes
Fox Brown Quick The