Friday, May 18, 2018

here docs

$x = <<<THE_END
PHP stands for "PHP: Hypertext Preprocessor".
The acronym "PHP" is therefore, usually referred to as a recursive acronym because the long form contains the acronym itself.
As this text is 'being' written in a here-doc there is no need to escape the double quotes.
THE_END;
print $x;
Output:
PHP stands for "PHP: Hypertext Preprocessor".
The acronym "PHP" is therefore, usually referred to as a recursive acronym because the long form contains the acronym itself.
As this text is 'being' written in a here-doc there is no need to escape the double quotes.

Access by reference

Function returning reference

$r = 10;
$ref = & funcByRef("r");
$ref = 12;
print $r;
function &funcByRef($v) {
 return $GLOBALS[$v];   
}
Output:
12

Function Parameter - access by reference

$r = 10;
funcByRefParam($r);
print $r;
function funcByRefParam(&$v) {
 $v--;
}
Output:
9

foreach

$array = array("01"=>"Joe", "02"=>"Martin", "03"=>"Sam");
foreach ($array as $key => $value) {
    print "$key=>$value\n";
}
print "Modify value\n";
$i = 1;
foreach ($array as $key => &$value) {    
    $value = $i.". ".$value;
    $i = $i +1;
}
foreach ($array as $k => $v) {
    print "$k=>$v\n";
}
Output:
01=>Joe
02=>Martin
03=>Sam
Modify value
01=>1. Joe
02=>2. Martin
03=>3. Sam

each

$array = array("01"=>"Joe", "02"=>"Martin", "03"=>"Sam");
reset($array);
$elements = each($array);
print "\$elements[\"0\"]=".$elements["0"]."\n";
print "\$elements[\"key\"]=".$elements["key"]."\n";
print "\$elements[\"1\"]=".$elements["1"]."\n";
print "\$elements[\"value\"]=".$elements["value"]."\n";
print "____________________________________\n";
$elements = each($array);
print "\$elements[\"0\"]=".$elements["0"]."\n";
print "\$elements[\"key\"]=".$elements["key"]."\n";
print "\$elements[\"1\"]=".$elements["1"]."\n";
print "\$elements[\"value\"]=".$elements["value"]."\n";
print "____________________________________\n";
reset($array);
while(list($k, $v)=each($array)) {
    print "$k=>$v\n";
}
Output:
$elements["0"]=01
$elements["key"]=01
$elements["1"]=Joe
$elements["value"]=Joe
____________________________________
$elements["0"]=02
$elements["key"]=02
$elements["1"]=Martin
$elements["value"]=Martin
____________________________________
01=>Joe
02=>Martin
03=>Sam

Setting array elements

$ary[] = "blue";
print $ary[0] . "\n";
$ary[] = "red";
print $ary[0] . "-" . $ary[1];
Output:
blue
blue-red

Saturday, May 20, 2017

fread

<?php
$file_reader = fopen("sample_text.txt", "r");
$content = fread($file_reader, 4);
echo $content;
?>
Output:
This

mb_substr

<?php
if (ini_get("mbstring.func_overload") & 2 != 0) {
    echo "ini_get(\"mbstring.func_overload\")" . "<br/>";
}
if (function_exists('mb_substr')) {
 echo "mb_substr exists";
}
?>

here docs

$x = <<<THE_END PHP stands for "PHP: Hypertext Preprocessor". The acronym "PHP" is therefore, usually referre...