CS174
Chris Pollett
Mar 1, 2021
$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++; }
Which of the following statements is true?
$fruits = preg_split("/\s+/", "apples oranges banana"); //notice the extra spaces between oranges and banana.would split on one or more white space characters. So in this case, $fruits = ['apples', 'oranges', 'banana'].
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )that let you find matches to regular expressions. In the above, [] arguments are optional.
preg_match
returns 1 (if pattern found), 0 otherwise.
preg_match_all
returns the number of matches or false
if the pattern is not found.
If a variable $matches
is supplied to the function call, then
it will be populated with either the first match found in preg_match
case,
or all matches in preg_match_all
case. $flags controls the format
of how $matches
will be populated, and $offset says at what character
to begin the search in $subject
.
preg_replace($pattern, $replacement, $subject)
function that let's you substitute regex $pattern matches with a string $replacement of your choice.