Snippets
Created by
Lauren Pittenger
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | <?php
function hello() {
return 'Hello, World';
}
// $greeting is equal to what our hello function returns
$greeting = hello();
echo $greeting;
/* *****
TWO
***** */
function hello($name) {
if($name == 'Lauren'){
return 'Hello, Lauren';
} else {
return 'Hello, stranger';
}
}
// $greeting is equal to what our hello function returns
$greeting = hello('Chris');
echo $greeting;
/* *****
THREE
***** */
function add_up($a, $b) {
$arr = array(
$a,
$b,
$a + $b
);
return $arr;
}
$value = add_up(2, 4);
// now we get back our sum value, but we also have the values that were passed in, in case we should need them.
echo $value[2]
/* *****
PHP VARIABLE FUNCTIONS
***** */
function answer(){
return 42;
}
function add_up($a, $b) {
return $a + $b;
}
$func = 'add_up';
$num = $func(5, 10);
/* *****
CLOSURES
anonymous functions that can access variables outside of the function scope
***** */
$name = 'Lauren';
$greet = function() use($name) {
echo "Hello, $name.";
};
$greet();
/* *****
BUILT-IN FUNCTIONS
***** */
// strlen -- return an integer of string length
$phrase = "We only hit what we aim for";
$len = strlen($phrase);
// echo $len;
// substr -- sub string -- returns a string starting at a position
substr($phrase, 0);
// strpos -- string position - find the first instance of a substring's position inside of a string
$start = strpos($phrase, 'hit');
echo substr($phrase, $start);
/* *****
ARRAY FUNCTIONS
***** */
$names = array(
'Mike' => 'Frog',
'Chris' => 'Teacher',
'Hampton' => 'Teacher'
);
var_dump(array_keys($names));
function print_info($value, $key){
echo "$key is a $value.";
}
array_walk($names, 'print_info');
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.