<?php
//contants
define ("SOME_CONSTANT", 28);
class Test{ const TEXT_MAX = 255; }
//out of the class
Test::TEXT_MAX
//inside the class
self::TEXT_MAX
//escape character and use variables in strings
echo "The value of \$a is $a";
//convert variables
$num = (float)3.5451;
$name = (string)$otherVar;
//get params in functions
func_num_args()
func_get_arg($arg_num)
func_get_args()
//variable variables
$a = 100;
$b = 'a';
echo $$b;
//100
//variable functions
$a = ($n % 2 ? "function1" : "function2");
$a($n);
//$a is the name of a function
//$method="getStreet1";
echo $order->getShippingAddress(){$function}();
//print html output of arrays, strings, numbers, objects...
print_r()
var_dump()
//Arrays
$a = array ('1' => 10, '11' => "test", 'another element');
echo $a[11];
//Errors
//Use: @ before an expression avoid any kind of error.
//Assigning values from an array
list ($a, $b, $c) = $array;
//Using for each loops
foreach ($array as $k => $v) {
//$k: index(0,1,2...)
//$v: value
}
reset($array); //reset counter to use for each
//While loops
while(list ($k, $v) = each ($array)){
//$k: index(0,1,2...)
//$v: value
}
//execute printout for each value of the array
array_walk ($array, 'printout');
//order the index of an array
ksort($array);
krsort($array);
//order values of on array
sort($array);
asort($array);
//Merge arrays
$a = array (10, 20, 30, 40);
$b = array (10, 20, 30, 40);
$array = array_merge ($a, $b);
//10, 20, 30, 40, 10, 20, 30, 40
//Intersect arrays
$a = array (‘a’ => 20, 36, 40);
$b = array (‘b’ => 20, 30, 40);
array_intersect ($a, $b);
//20, 40
//Create an array from a comma separated string
explode(',',$string_text);
//Power of arrays and strings
$emoticons = array(
':)' => '<img src="/smiley.png"/>',
';)' => '<img src="/wink.png"/>'
);
$new_subject = str_replace(array_keys($emoticons), array_values($emoticons), $subject);
//dates
$yesterday = localtime(time() - 24*60*60, 1);
//dates
print "The local ISO-8601 date string is ". date('Y-m-d\TH:i:sO');
//if Statement:
$marginPosition = ($profile->getThumbnailAlign() == "left")
? "float: left; margin-right: 10px;"
: "float: right; margin-left: 10px;";
//Benefics:
// 1) It's immediately clear that the intent of the statement is to assign a value to $variable.
// 2) By typing the equivalence condition with the literal on the left, you reduce the spread of a whole class of bugs. This tricks dates back to C, at least.
// 3) When checking equivalence for strings, the "===" operator is a bit faster (no type checking/cast needed).
//strpos return 0 or false
$mystring = "Hello World!";
$findme = "You will not find me";
$pos = strpos($mystring, $findme);
if ($pos === false) {
//with 3 equals we make sure that the function returns false and
// not misunderstand 0 for false
}
?>
Tags: arrays, constant, foreach index, number to string, order array, variable of variable