Saturday, April 29, 2017

call_user_func

<?php
 $e = "n * 2";
 function incr($expression) {
  $expression = str_replace('n', '$n', $expression);  
  
  $func_body = "
   \$increment = (int)($expression + 1);
   return \$increment;";
  return create_function('$n', $func_body);
 }
 $increment_func = incr($e);
 echo call_user_func($increment_func, 2);
?>
Output:
5

create_function

<?php
 $e = "n * 2";
 function incr($expression) {
  $expression = str_replace('n', '$n', $expression);  
  
  $func_body = "
   \$increment = (int)($expression + 1);
   return \$increment;";
   echo("Func body: " . $func_body);
  return create_function('$n', $func_body);
 }
 $increment_func = incr($e);
 echo $increment_func(2) . "<br/>";
?>
Output:
Func body: $increment = (int)($n * 2 + 1); return $increment;
5

Friday, April 28, 2017

str_repeat

<?php
    echo parenthesize('a == b ? c : (d == e ? x : y)');
    function parenthesize($expression) {
  $expression .= ';';
  $res = '';
  $depth = 0;
  for ($i = 0; $i < strlen($expression); ++$i) {
   $char = $expression[$i];
   switch ($char) {
    case '?':
     $res .= ' ? (';
     $depth++;
     break;
    case ':':
     $res .= ') : (';
     break;
    case ';':
     $res .= str_repeat(')', $depth) . ';';
     $depth= 0;
     break;
    default:
     $res .= $char;
   }
  }
  return rtrim($res, ';');
 }
?>
Output:
hello 
php
php
ello 

trim, ltrim, rtrim examples

<?php
    echo rtrim('hello php', 'php') . '<br/>';
    echo ltrim('hello php', 'hello') . '<br/>';
    echo trim('hello php', 'hello') . '<br/>';
    echo trim('hello php', 'php') . '<br/>'; 
?>
Output:
hello 
php
php
ello 

list example

<?php
$colors = array("blue", "red", "green");
list($blue, $red, $green) = $colors;
echo "colors: $blue $red $green";
?>
Output:
colors: blue red green

Monday, April 24, 2017

List files in a directory

<?php
$dir    = '../../../kindle/K';
$files = scandir($dir);
$i = 1;
foreach ($files as $key=>$value) {
 if (preg_match('/^[a-z]/i', $value)) {
  echo $i++ . "\t" . $value . "<br/>";
 }
}
?>

Modifying by reference

<?php
$x = 2;
echo "x is ".$x."<br/>";
$y = &$x;
$x = 3;
echo "assign x=" . $x . "<br/>";
echo "y is ".$y . "<br/>";
function modifyref(&$m) {
 $m = 5;
 echo $m . "<br/>";
}
echo "modify \$y ref to ";
modifyref($y);
echo "x is ". $x . "<br/>";
echo "y is ".$y;
?>
Output:
x is 2
assign x=3
y is 3
modify $y ref to 5
x is 5
y is 5

equality and identity check

<?php 
 $bool = true;
 $ibool = 1;
 $sbool = "true";
 $sbool1 = "true";
 
 echo "\$bool equals \$ibool? " . ($bool == $ibool) . "<br/>";
 
 if ($bool === $ibool):
 echo "\$bool same datatype as \$ibool";
 else:
 echo "\$bool not of same datatype as \$ibool";
 endif;
 
 echo "<br/>";
 echo "\$bool equals \$sbool? " .($bool == $sbool) . "<br/>";
 
 if ($bool === $sbool):
 echo "\$bool same datatype as \$sbool";
 else:
 echo "\$bool not of same datatype as \$sbool";
 endif;
 
 echo "<br/>";
 echo "\$sbool identical to \$sbool1? " .($sbool === $sbool1);
 
?>
Output:
$bool equals $ibool? 1
$bool not of same datatype as $ibool
$bool equals $sbool? 1
$bool not of same datatype as $sbool
$sbool identical to $sbool1? 1

Class exists

<?php
if (! class_exists('Article', false)):
echo "Class Article doesn't exists, load class<br/>";
class Article { 
}
else:
echo "Class Article exists!<br/>";
endif;

if (class_exists('Article', false)):
echo "Class Article exists!";
endif;
?>
Output:
Class Article doesn't exists, load class
Class Article exists!

Thursday, April 20, 2017

Class Example

<?php
class Article {
 public $name;
 public $main_category;
 public $tags = array();
 public $is_published = false;
 
 function __construct( $args = array(), $tags = array() ) {
  $this->tags = $tags;
  foreach ($args as $varname => $value) {
   echo "assign " . $varname . " to " . $value . "<br/>";
   $this->$varname = $value;
  }
 } 
 function category() {
  return $this->main_category;
 }
}
$article = new Article(array('name' => "Php Global Variable", 'main_category' => "Php Variables", 'is_published' => true), array("php"));

echo "Name: " . $article->{'name'} . ", Category: " . $article->{'category'}();

?>
Output:
assign name to Php Global Variable
assign main_category to Php Variables
assign is_published to 1
Name: Php Global Variable, Category: Php Variables

array_unique

<?php
$colors = array("blue", "red", "green", "blue");
$colors = array_unique($colors);
var_dump($colors);
?>
Output:
array(3) { [0]=> string(4) "blue" [1]=> string(3) "red" [2]=> string(5) "green" }

array_merge

<?php
$books = array ("PhpCookbook", "PhpRecipies");
$electronics = array("Tab", "Laptop", "Mobile");
$products = array_merge($books, $electronics);
var_dump($products);
?>
Output:
array(5) { [0]=> string(11) "PhpCookbook" [1]=> string(11) "PhpRecipies" [2]=> string(3) "Tab" [3]=> string(6) "Laptop" [4]=> string(6) "Mobile" }

str_replace

<?php
$value = "abc def";
echo "\$value is " . $value . "<br/>";
$replace_a_with_x = str_replace("a", "x", $value);
echo "\$replace_a_with_x is: " . $replace_a_with_x . "<br/>";
$replace_array_of_char_with_num = str_replace(array("a", "b", "c"), 1, $value);
echo "\$replace_array_of_char_with_num is: " . $replace_array_of_char_with_num . "<br/>";
$replace_array_of_char_with_num_array = str_replace(array("a", "b", "c"), array(1, 2, 3), $value);
echo "\$replace_array_of_char_with_num_array is: " . $replace_array_of_char_with_num_array . "<br/>";
?>
Output:
$value is abc def
$replace_a_with_x is: xbc def
$replace_array_of_char_with_num is: 111 def
$replace_array_of_char_with_num_array is: 123 def

require

<?php
echo "Echo BLOG<br/>";
require(dirname(__FILE__) . "/constants.php");
echo "after loading constants...<br/>BLOG: " . BLOG . "<br/>";
echo "Load again <br/>";
require(dirname(__FILE__) . "/constants.php");
echo "Load again using require_once <br/>";
require_once(dirname(__FILE__) . "/constants.php");
?>
Output:
Echo BLOG
Define constants:
php cookbook
Constant ARTICLE_NAME not defined, define now 
Constant ARTICLE_NAME defined 
after loading constants...
BLOG: php cookbook
Load again 
Define constants:

Notice: Constant BLOG already defined in C:\phpProjects\examples\constants.php on line 3
php cookbook
Load again using require_once 

Constants

<?php
echo "<Define constants:<br/>";
define('BLOG', "php cookbook");
echo BLOG . "<br/>";
if (!defined('ARTICLE_NAME')) {
 echo "Constant ARTICLE_NAME not defined, define now <br/>";
 define('ARTICLE_NAME', "php constants"); 
 echo "Constant ARTICLE_NAME defined <br/>";
}
Output:
Define constants:
php cookbook
Constant ARTICLE_NAME not defined, define now 
Constant ARTICLE_NAME defined 

Static Variable

<?php
$counter = 5;
function init() {
 static $counter = 1;
 $counter++;
 echo "<br/> within function init(): \$counter: " . $counter . "<br/>";
}
echo "In script, \$counter: " . $counter;
init();
echo "In script, after init(), \$counter: " . $counter;
init();
?>
Output:
In script, $counter: 5
within function init(): $counter: 2
In script, after init(), $counter: 5
within function init(): $counter: 3

Wednesday, April 19, 2017

Php version

<?php
$phpVersion = phpversion();
$phpVersionCompare = "5.6.8";
echo "phpversion:" . $phpVersion . "<br/>";
echo "compare $phpVersionCompare < $phpVersion? " . version_compare( $phpVersionCompare, $phpVersion, '<' );
?>
Output:
phpversion:5.6.9
compare 5.6.8 < 5.6.9? 1

String functions

<?php
$value = "Find string position...";
echo "Position of 'position' in $value is " . strpos($value, 'position') . "<br/>";
echo "Length of $value is " . strlen($value);
?>
Output:
Position of 'position' in Find string position... is 12
Length of Find string position... is 23

Monday, April 17, 2017

Superglobals

<?php
 $super_globals = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() );
 foreach ( $super_globals as $k => $v ) {
  echo "$k=>" . "$v" . "<br/>";
 }
?>  
Output:
HTTP_HOST=>localhost:8080
HTTP_CONNECTION=>keep-alive
HTTP_CACHE_CONTROL=>max-age=0
HTTP_UPGRADE_INSECURE_REQUESTS=>1
HTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
HTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
HTTP_ACCEPT_ENCODING=>gzip, deflate, sdch, br
HTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.8
PATH=>...
SystemRoot=>C:\WINDOWS
COMSPEC=>C:\WINDOWS\system32\cmd.exe
PATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PL;.PY
WINDIR=>C:\WINDOWS
SERVER_SIGNATURE=>
SERVER_SOFTWARE=>Apache/2.4.12 (Win32) mod_jk/1.2.40 PHP/5.6.9
SERVER_NAME=>localhost
SERVER_ADDR=>::1
SERVER_PORT=>8080
REMOTE_ADDR=>::1
DOCUMENT_ROOT=>C:/phpProjects
REQUEST_SCHEME=>http
CONTEXT_PREFIX=>
CONTEXT_DOCUMENT_ROOT=>C:/phpProjects
SERVER_ADMIN=>admin@example.com
SCRIPT_FILENAME=>C:/phpProjects/examples/superglobals.php
REMOTE_PORT=>56117
GATEWAY_INTERFACE=>CGI/1.1
SERVER_PROTOCOL=>HTTP/1.1
REQUEST_METHOD=>GET
QUERY_STRING=>
REQUEST_URI=>/examples/superglobals.php
SCRIPT_NAME=>/examples/superglobals.php
PHP_SELF=>/examples/superglobals.php
REQUEST_TIME_FLOAT=>1492427533.981
REQUEST_TIME=>1492427533

Superglobal $GLOBALS

$GLOBALS represents an array of global variables, a function can use the global variables array instead of defining a global variable.
<?php 
global $blog_id;
$blog_id = "phpCookbook";
function intialize_global() {
 echo "intialize_global: before assign, \$GLOBALS['blog_id']=". $GLOBALS['blog_id'] . "<br/>"; 
 $GLOBALS['blog_id'] = "intialize_global";
 echo "intialize_global: after assign, \$blog_id=". $blog_id . "<br/>"; 
 echo "intialize_global: after assign, \$GLOBALS['blog_id']=". $GLOBALS['blog_id'] . "<br/>"; 
}
echo "before initialize_global: " . $blog_id . "<br/>";
intialize_global();
echo "after initialize_global: " . $blog_id . "<br/>";
?>
Output:
before initialize_global: phpCookbook
intialize_global: before assign, $GLOBALS['blog_id']=phpCookbook

Notice: Undefined variable: blog_id in C:\phpProjects\examples\superglobal_globals.php on line 7
intialize_global: after assign, $blog_id=
intialize_global: after assign, $GLOBALS['blog_id']=intialize_global
after initialize_global: intialize_global

Saturday, April 15, 2017

Global variable

Variables declared as global within a function would be able to the access the global variable defined by the same name. If not defined using global then the function will encounter 'Undefined variable' error.
<?php 
global $blog_id;
$blog_id = "phpCookbook";
function access_constant() {
 echo "access_constant: before assign, \$blog_id=". $blog_id . "<br/>"; 
 $blog_id  = "access_constant";
 echo "access_constant: after assign, \$blog_id=". $blog_id . "<br/>"; 
}
function initialize_constant() {
 global $blog_id;
 $blog_id  = "initialize_constant";
 echo "initialize_constant: after assign, \$blog_id=". $blog_id . "<br/>";
}
echo "before access_constant: " . $blog_id . "<br/>";
access_constant();
echo "after access_constant: " . $blog_id . "<br/>";
echo "before initialize_constant: " . $blog_id . "<br/>";
initialize_constant();
echo "after initialize_constant: " . $blog_id . "<br/>";
?>
Output:
before access_constant: phpCookbook

Notice: Undefined variable: blog_id in C:\phpProjects\examples\global.php on line 5
access_constant: before assign, $blog_id=
access_constant: after assign, $blog_id=access_constant
after access_constant: phpCookbook
before initialize_constant: phpCookbook
initialize_constant: after assign, $blog_id=initialize_constant
after initialize_constant: initialize_constant

Another example

<?php
$x= "This is X";
$y = "This is Y";
print $x."\n";
printGlobal();
function printGlobal() {
    global $x;
    global $y;
    print "Within print global\n";
    print $GLOBALS["x"]."\n";
    print $y."\n";    
}
function callHeader() {
    global $request;        
    if (!isset($request['header'])) {
        $request['header'] = 0;
    } else {
        ++$request['header'];
    }
    print $request['header'] . "\n";
}
callHeader();
callHeader();
print $GLOBALS['request']['header'] . "\n";
global $request;
print $request['header'];
?>
Output:
This is X
Within print global
This is X
This is Y
0
1
1
1

in_array example

<?php
$menu = array("indian", "conitnental", "chinsese");
if (!in_array("seafood", $menu)) {
 echo "seafood not in menu-";
}
if (in_array("indian", $menu)) {
 echo "indian in menu";
}
?>
Output:
seafood not in menu-indian in menu

Wednesday, April 12, 2017

Multi-dimension array example

<?php
$menu=array("food" => array("continental"=>"bread", "chinese"=>"noodles"),
            "languages"=> array("functional"=>"scala", "script"=>"perl", "web"=>"php"));
foreach($menu as $key=>$value) {
 echo "$key "."=>"."$value <br/>";
 echo "___________________________<br/>";
 echo "foreach starts <br/>";
 echo "___________________________<br/>";
 foreach($value as $key1=>$value1) {
  echo "$key1 "."=>"."$value1 <br/>";
 }
 echo "___________________________<br/>";
 echo "foreach ends<br/>"; 
 echo "___________________________<br/>";
}
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><br/>";
foreach($menu as $key=>$value) {
 echo "$key "."=>"."$value <br/>";
 echo "___________________________<br/>";
 echo "each(\$value):". each($value) . "<br/>";
 echo "___________________________<br/>";
 while(list($key1, $value1)=each($value)) {
  echo $key1 . "=" . $value1 . "<br/>";
 }
 echo "___________________________<br/>";
}
echo "Continental food: ".$menu['food']['continental']; 
echo var_dump($menu);
?>
Output:
food =>Array 
___________________________
foreach starts 
___________________________
continental =>bread 
chinese =>noodles 
___________________________
foreach ends
___________________________
languages =>Array 
___________________________
foreach starts 
___________________________
functional =>scala 
script =>perl 
web =>php 
___________________________
foreach ends
___________________________
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
food =>Array 
___________________________
each($value):Array
___________________________
chinese=noodles
___________________________
languages =>Array 
___________________________
each($value):Array
___________________________
script=perl
web=php
___________________________
Continental food: breadarray(2) { ["food"]=> array(2) { ["continental"]=> string(5) "bread" ["chinese"]=> string(7) "noodles" } ["languages"]=> array(3) { ["functional"]=> string(5) "scala" ["script"]=> string(4) "perl" ["web"]=> string(3) "php" } }

Array examples

<?php
$db[]="Oracle";
$db[]="Mysql";
echo "is_array?" . is_array($db) . "<br/>";
echo "\$db[0]=$db[0] \$db[1]=$db[1]<br/>";
$count = count($db);
echo "count of db array: $count<br/>";
$dbver["oracle"]="12";
echo "\$dbver['oracle']=". $dbver["oracle"]. "<br/>";
$topics = array('db' => 'Mysql', 'language' => 'php');
foreach($topics as $key=>$value) {
 echo "$key $value<br/>";
}
$topics = array("Mysql", "Oracle");
foreach($topics as $key=>$value) {
 echo "$key $value<br/>";
}
?>
Output:
is_array?1
$db[0]=Oracle $db[1]=Mysql
count of db array: 2
$dbver['oracle']=12
db Mysql
language php
0 Mysql
1 Oracle

Tuesday, April 11, 2017

isset example

<?php 
echo "Is \$header set? " . (isset($header) ? 'yes' : 'no') . "<br/>";
$header = true;
echo "After setting \$header=$header" . "<br/>";
echo "Is \$header set? " . (isset($header) ? 'yes' : 'no') . "<br/>";
echo "Is \$header empty? " . (empty($header) ? 'yes' : 'no') . "<br/>";
echo "Unset \$header" . "<br/>";
unset($header);
echo "Is \$header set? " . (isset($header) ? 'yes' : 'no') . "<br/>";
echo "Is \$header empty? " . (empty($header) ? 'yes' : 'no') . "<br/>";
?>
Output:
Is $header set? no
After setting $header=1
Is $header set? yes
Is $header empty? no
Unset $header
Is $header set? no
Is $header empty? yes

How to find the current file and directory?

<?php 
echo  __FILE__."<br/>";
echo dirname( __FILE__ ) . '\other.php'
?>
Output:
C:\phpProjects\examples\dirname.php
C:\phpProjects\examples\other.php

here docs

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