0% found this document useful (0 votes)
3 views40 pages

Ch7 - Osp With PHP

The document provides an overview of open source programming with PHP, discussing the differences between static and dynamic websites. It explains the benefits of dynamic content, the installation of PHP, and the role of server-side scripting languages in generating dynamic web pages. Additionally, it introduces PHP as a server-side scripting language that manages dynamic content and integrates with various databases.

Uploaded by

biwesh rajbanshi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

Ch7 - Osp With PHP

The document provides an overview of open source programming with PHP, discussing the differences between static and dynamic websites. It explains the benefits of dynamic content, the installation of PHP, and the role of server-side scripting languages in generating dynamic web pages. Additionally, it introduces PHP as a server-side scripting language that manages dynamic content and integrates with various databases.

Uploaded by

biwesh rajbanshi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

 

 
 
 
 
 
 
 
7.  OPEN  SOURCE  PROGRAMMING  
WITH  

PHP  
 
 
 
   

  [Link]  -­‐  1  
 
INTRODUCTION  
Static  vs.  Dynamic  websites  
A  static  website  is  created  using  HTML  pages  which  have  been  written  in  a  fixed  way  to  instruct  the  browser  how  
to   render   the   page.   (What   You   See   Is   What   You   Get).   Static   websites   are   used   to   display   fixed   information   that  
does   not   need   to   be   updated   on   a   regular   basis.   As   the   Web   evolved,   sites   became   more   complex   and   were  
expected  to  display  dynamic  information  that  could  not  have  been  “hard  coded”  in  HTML.  
 
Dynamic  websites  
The   solution   was   to   generate   the   HTML   “on-­‐the-­‐fly”   based   on   parameters   and   specifications.   For   example,   if   a  
user  asks  to  see  search  results,  a  unique  page  would  be  generated  specifically  for  him.  Since  there  is  no  way  of  
knowing   every   possible   search   result   for   every   possible   keyword,   the   final   page   is   being   assembled   using   a  
server-­‐side   script.   The   server-­‐side   script   constructs   the   page   and   then   it   is   being   sent   back   to   the   client.   This  
means  that  the  page  [Link]  will  look  different  each  time  based  on  the  given  specifications.  
Every   client   makes   a   request   for   a   page.   The   server   checks   what   the   client   has   asked   for   and   based   on   that,   it  
constructs  a  page  for  him  on  an  existing  template.  The  template  is  a  page,  which  contains  HTML  code  and  server-­‐
side  code  that  will  end  up  as  HTML  code  as  well,  but  a  different  HTML  each  time.  
 
Three  Tier  Web  Applications  

 
Benefits  Of  Dynamic  Content  
• The  ability  to  customize  pages  for  any  given  user.  
• Greater  ease  of  modification  and  update.  
• Extended  functionality  (login,  transactions,  communication  etc.).  
• Automating  the  site  and  allowing  it  to  support  itself.  Fewer  pages  to  be  created  manually.  
 

PHP  Parser  Installation:  

Before   you   proceed   it   is   important   to   make   sure   that   you   have   proper   environment   setup   on   your   machine   to  
develop  your  web  programs  using  PHP.  Type  the  following  address  into  your  browser's  address  box.  

[Link]  or  [Link]  

  [Link]  -­‐  2  
 
If   this   displays   a   page   showing   your   PHP   installation   related   information   then   it   means   you   have   PHP   and  
Webserver  installed  properly.  Otherwise  you  have  to  follow  given  procedure  to  install  PHP  on  your  computer.  

 
Server-­‐Side  Scripting  
In  order  to  generate  dynamic  pages  we  use  a  server-­‐side  scripting  language.  There  are  different  types  of  server-­‐
side  scripting  languages  such  as  PHP,  ASP,  [Link],  ColdFusion,  JavaServer  Pages,  Perl  and  others.  Each  scripting  
languages   is   being   interpreted   by   an   application,   just   as   Flash   is   used   to   make   sense   of   ActionScript   and   have   the  
code  do  things.  The  application  which  interprets  the  server-­‐side  script  is  installed  on  the  sever  just  like  any  other  
application.  
 
Server-­‐side  scripting  languages  are  also  operating  systems  dependent.  PHP  for  example,  is  being  interpreted  by  
an  application  called  Apache.  Each  server-­‐side  scripting  language  supports  basic  programming  concepts  such  as  
variables,   arrays,   functions,   loops,   conditional   statement   and   others.   They   also   contain   more   specific   elements  
such  as  special  objects,  commands  used  to  communicate  with  the  server  and  a  database  and  much  more.  
 
Server-­‐Side  Scripting  &  Databases  
When  there  is  a  need  to  store  and  retrieve  information  (members,  items  in  stock  etc.)  a  database  will  be  used  to  
contain  the  data.  Sever-­‐side  script  can  communicate  to  a  database  using  a  structured  query  language(SQL)  which  
manipulates  the  database  (add,  remove,  update,  delete  etc.)  
 
What  is  PHP?  

PHP   started   out   as   a   small   open   source   project   that   evolved   as   more   and   more   people   found   out   how   useful   it  
was.  Rasmus  Lerdorf  unleashed  the  first  version  of  PHP  way  back  in  1994.  

• PHP  stands  for  ‘PHP:  Hypertext  Preprocessor’.  


• PHP   is   a   server   side   scripting   language   that   is   embedded   in   HTML.   It   is   used   to   manage   dynamic   content,  
databases,  session  tracking,  even  build  entire  e-­‐commerce  sites.  
• It   is   integrated   with   a   number   of   popular   databases,   including   MySQL,   PostgreSQL,   Oracle,   Sybase,  
Informix,  and  Microsoft  SQL  Server.  
• PHP   is   pleasingly   zippy   in   its   execution,   especially   when   compiled   as   an   Apache   module   on   the   Unix   side.  
The   MySQL   server,   once   started,   executes   even   very   complex   queries   with   huge   result   sets   in   record-­‐
setting  time.  
• PHP   supports   a   large   number   of   major   protocols   such   as   POP3,   IMAP,   and   LDAP.   PHP4   added   support   for  
Java  and  distributed  object  architectures  (COM  and  CORBA),  making  n-­‐tier  development  a  possibility  for  
the  first  time.  
• PHP  is  forgiving:  PHP  language  tries  to  be  as  forgiving  as  possible.  
• PHP  Syntax  is  C-­‐Like.  
• PHP  is  an  open  source  software  (OSS),  This  means  it’s  free  to  use  and  isn’t  being  controlled  by  a  single  
entity.  
• It  is  being  developed  by  a  group  of  developers.  
• PHP  syntax  resembles  that  of  JavaScript  and  ActionScript  in  different  ways.  
• PHP  is  free  to  download  and  use  
• PHP  files  may  contain  text,  HTML  tags  and  scripts.  
• PHP  files  are  returned  to  the  browser  as  plain  HTML.  
• PHP  files  have  a  file  extension  of  ".php",  ".php3",  or  ".phtml".  
• PHP  can  be  written  in  any  text  editor.  
• PHP  script  will  be  located  inside  special  tags,  much  like  JavaScript  
  [Link]  -­‐  3  
 
e.g.  <?php  //php  script  here  ?>  
• PHP  code  can  be  located  any  where  in  the  page.  
• PHP  is  case  sensitive.  
• Every  variable  in  PHP  will  have  the  $  symbol  as  a  prefix  
e.g.  $myCollege  =“KCC”;  
• Every  line  of  code  MUST  be  terminated  with  a  semicolon  ‘;’.  
 

Common  uses  of  PHP:  

• PHP  performs  system  functions,  i.e.  from  files  on  a  system  it  can  create,  open,  read,  write,  and  close  them.  
• PHP  can  handle  forms,  i.e.  gather  data  from  files,  save  data  to  a  file,  thru  email  you  can  send  data,  return  
data  to  the  user.  
• You  add,  delete,  and  modify  elements  within  your  database  thru  PHP.  
• Access  cookies  variables  and  set  cookies.  
• Using  PHP,  you  can  restrict  users  to  access  some  pages  of  your  website.  
• It  can  encrypt  data.  

What  is  MySQL?  


• MySQL  is  a  database  server.  
• MySQL  is  ideal  for  small  and  medium  applications.  
• MySQL  supports  standard  SQL.  
• MySQL  compiles  on  a  number  of  platforms.  
• MySQL  is  free  to  download  and  use.  
 
PHP  +  MySQL  
PHP   combined   with   MySQL   is   cross-­‐platform   (Means   that   you   can   develop   in   Windows   and   serve   on   a   Linux  
platform  as  well).  
 
Why  PHP?  
• PHP  runs  on  different  platforms  (Windows,  Linux,  Unix,  etc.)  
• PHP  is  compatible  with  almost  all  servers  used  today  (Apache,  IIS,  etc.)  
• PHP  is  FREE  to  download  from  the  official  PHP  resource:  [Link]  
• PHP  is  easy  to  learn  and  runs  efficiently  on  the  server  side.  
• Reduce  the  time  to  create  large  websites.  
• Create  a  customized  user  experience  for  visitors  based  on  information  that  you  have  gathered  from  them.  
• Open  up  thousands  of  possibilities  for  online  tools  like  shopping  carts  for  e-­‐commerce  websites.  

What    you    should    Know?  

Before  starting  this  tutorial  it  is  important  that  you  have  a  basic  understanding  and  experience  in  the  
following:  

• HTML  -­‐  Know  the  syntax  and  especially  HTML  Forms.  


• Basic  programming  knowledge  -­‐  This  isn't  required,  but  if  you  have  any  traditional  programming  
experience  it  will  make  learning  PHP  a  great  deal  easier.  

 
<?PHP  …  ?>  

  [Link]  -­‐  4  
 
Syntax,  Variables  &  Strings  
Basic  PHP  Syntax  
You  cannot  view  the  PHP  source  code  by  selecting  "View  source"  in  the  browser  –  you  will  only  see  the  output  
from   the   PHP   file,   which   is   plain   HTML.   This   is   because   the   scripts   are   executed   on   the   server   before   the   result   is  
sent  back  to  the  browser.  A  PHP  scripting  block  always  starts  with  <?php  and  ends  with  ?>.  A  PHP  scripting  block  
can  be  placed  anywhere  in  the  document.  On  servers  with  shorthand  support  enabled  you  can  start  a  scripting  
block   with   <?   and   end   with   ?>.   However,  for  maximum  compatibility,  recommended  is  that  you  use  the  standard  
form  (<?php)  rather  than  the  shorthand  form.  
<?php  …  ?>  
 
A  PHP  file  normally  contains  HTML  tags,  just  like  an  HTML  file,  and  some  PHP  scripting  code.  
<html>  
<body>  
<?php  
echo  "Hello  World";  
?>  
</body>  
</html>  
 
Each  code  line  in  PHP  must  end  with  a  semicolon.  The  semicolon  is  a  separator  and  is  used  to  distinguish  one  set  
of   instructions   from   another.   There   are   two   basic   statements   to   output   text   with   PHP:   echo   and   print.   In   the  
example  above  we  have  used  the  echo  statement  to  output  the  text  "Hello  World".  
 
Comments  In  PHP  
In  PHP,  we  use  //  to  make  a  single-­‐line  comment  or  /*  and  */  to  make  a  large  comment  block.  
<html>  
<body>  
<?php  
//This  is  a  comment  
 
/*  
This  is  a  comment  block.  
*/  
?>  
</body>  
</html>  
 
PHP  Variables  
Variables  are  used  for  storing  a  value,  like  text  strings,  numbers  or  arrays.  When  a  variable  is  set  it  can  be  used  
over  and  over  again  in  your  script.  All  variables  in  PHP  start  with  a  $  sign  symbol.  The  correct  way  of  setting  a  
variable  in  PHP:  
$var_name  =  value;  
 
New  PHP  programmers  often  forget  the  $  sign  at  the  beginning  of  the  variable.  In  that  case  it  will  not  work.  Let's  
try  creating  a  variable  with  a  string,  and  a  variable  with  a  number:  
<?php  
$txt  =  "Hello  World!";  
$number  =  16;  
?>  

  [Link]  -­‐  5  
 
 
PHP  is  a  Loosely  Typed  Language  
In  PHP  a  variable  does  not  need  to  be  declared  before  being  set.  In  the  previous  example,  you  see  that  you  do  not  
have   to   tell   PHP  which   data  type   the  variable  is.   PHP   automatically   converts   the   variable   to   the   correct  data  type,  
depending   on   how   they   are   set.   In   a   strongly   typed   programming   language,   you   have   to   declare   (define)   the   type  
and   name   of   the   variable   before   using   it   (Like   in   C,   C++   Programming.).   In   PHP   the   variable   is   declared  
automatically  when  you  use  it.  
 
Variable  Naming  Rules  
• A  variable  name  must  start  with  a  letter  or  an  underscore  "_".  
• A  variable  name  can  only  contain  alpha-­‐numeric  characters  and  underscores  (a-­‐Z,  0-­‐9,  and  _  ).  
• A  variable  name  should  not  contain  spaces.  If  a  variable  name  is  more  than  one  word,  it  should  be  
separated  with  underscore  ($my_string),  or  with  capitalization  ($myString).  
 

PHP  Variable  Scope  

The  scope  of  a  variable  is  the  portion  of  the  script  in  which  the  variable  can  be  referenced.  

PHP  has  four  different  variable  scopes:  

• local  
• global  
• static  
• parameter  

 
Local  Scope  

A  variable  declared  within  a  PHP  function  is  local  and  can  only  be  accessed  within  that  function.  (the  variable  has  
local  scope):  

<?php  
$a  =  5;  //  global  scope  
 
function  myTest()  
{  
echo  $a;  //  local  scope  
}    
 
myTest();  
?>  

The   script   above   will   not   produce   any   output   because   the   echo   statement   refers   to   the   local   scope   variable   $a,  
which   has   not   been   assigned   a   value   within   this   scope.   You   can   have   local   variables   with   the   same   name   in  
different  functions,  because  local  variables  are  only  recognized  by  the  function  in  which  they  are  declared.  Local  
variables  are  deleted  as  soon  as  the  function  is  completed.  

  [Link]  -­‐  6  
 
Global  Scope  

Global  scope  refers  to  any  variable  that  is  defined  outside  of  any  function.  Global  variables  can  be  accessed  from  
any   part   of   the   script   that   is   not   inside   a   function.   To   access   a   global   variable   from   within   a   function,   use  
the  global  keyword:  

<?php  
$a  =  5;  
$b  =  10;  
 
function  myTest()  
{  
global  $a,  $b;  
$b  =  $a  +  $b;  
}    
 
myTest();  
echo  $b;  
?>  

The  script  above  will  output  15.  

PHP  also  stores  all  global  variables  in  an  array  called  $GLOBALS[index].  Its  index  is  the  name  of  the  variable.  This  
array  is  also  accessible  from  within  functions  and  can  be  used  to  update  global  variables  directly.  The  example  
above  can  be  rewritten  as  this:  

<?php  
$a  =  5;  
$b  =  10;  
 
function  myTest()  
{  
$GLOBALS['b']  =  $GLOBALS['a']  +  $GLOBALS['b'];  
}    
 
myTest();  
echo  $b;  
?>  
 
Static  Scope  

When  a  function  is  completed,  all  of  its  variables  are  normally  deleted.  However,  sometimes  you  want  a  local  
variable  to  not  be  deleted.  

To  do  this,  use  the  static  keyword  when  you  first  declare  the  variable:  

static  $rememberMe;  

  [Link]  -­‐  7  
 
Then,  each  time  the  function  is  called,  that  variable  will  still  have  the  information  it  contained  from  the  last  time  
the  function  was  called.  

Note:  The  variable  is  still  local  to  the  function.  

Parameters  

A  parameter  is  a  local  variable  whose  value  is  passed  to  the  function  by  the  calling  code.  Parameters  are  declared  
in  a  parameter  list  as  part  of  the  function  declaration:  

function  myTest($para1,$para2,...)  
{  
           //  function  code  
}  

Parameters  are  also  called  arguments.    

Strings  In  PHP  


• String  variables  are  used  for  values  that  contain  character  strings.  
• After  we  create  a  string  we  can  manipulate  it.  A  string  can  be  used  directly  in  a  function  or  it  can  be  stored  
in  a  variable.  
Below,  the  PHP  script  assigns  the  string  "Hello  World"  to  a  string  variable  called  $txt:  
<?php  
$txt="Hello  World";  
echo  $txt;  
?>  
The  output  of  the  code  will  be:  
Hello  World  
 
PHP  -­‐  string  creation  single  quotes  

Thus   far   we   have   created   strings   using   double-­‐quotes,   but   it   is   just   as   correct   to   create   a   string   using   single-­‐
quotes,  otherwise  known  as  apostrophes.  

PHP  Code:  
$my_string  =  'KCC  -­‐  Unlock  your  potential!';  echo  'KCC  -­‐  Unlock  your  potential!';  echo  $my_string;    

If  you  want  to  use  a  single-­‐quote  within  the  string  you  have  to  escape  the  single-­‐quote  with  a  backslash  \  .  Like  
this:  \'  !  

PHP  Code:  
echo  'It\'s  Neat!';    

 
PHP  -­‐  string  creation  double-­‐quotes  

  [Link]  -­‐  8  
 
We  have  used  double-­‐quotes  and  will  continue  to  use  them  as  the  primary  method  for  forming  strings.  Double-­‐
quotes  allow  for  many  special  escaped  characters  to  be  used  that  you  cannot  do  with  a  single-­‐quote  string.  Once  
again,  a  backslash  is  used  to  escape  a  character.  

PHP  Code:  
$newline  =  "A  newline  is  \n";  $return  =  "A  carriage  return  is  \r";  $tab  =  "A  tab  is  \t";  $dollar  =  "A  dollar  sign  is  
\$";  $doublequote  =  "A  double-­‐quote  is  \"";    

Note:  If  you  try  to  escape  a  character  that  doesn't  need  to  be,  such  as  an  apostrophe,  then  the  backslash  will  show  
up  when  you  output  the  string.  

These   escaped   characters   are   not   very   useful   for   outputting   to   a   web   page   because   HTML   ignore   extra   white  
space.   A   tab,   newline,   and   carriage   return   are   all   examples   of   extra   (ignorable)   white   space.   However,   when  
writing  to  a  file  that  may  be  read  by  human  eyes  these  escaped  characters  are  a  valuable  tool!  

PHP  -­‐  string  creation  heredoc  

The   two   methods   above   are   the   traditional   way   to   create   strings   in   most   programming   languages.   PHP  
introduces   a   more   robust   string   creation   tool   called   heredoc  that   lets   the   programmer   create   multi-­‐line   strings  
without  using  quotations.  However,  creating  a  string  using  heredoc  is  more  difficult  and  can  lead  to  problems  if  
you  do  not  properly  code  your  string!  Here's  how  to  do  it:  

PHP  Code:  
$my_string  =  <<<TEST    
'KCC  -­‐  Unlock  your  potential    
TEST;      
echo  $my_string;    

There  are  a  few  very  important  things  to  remember  when  using  heredoc.  

• Use  <<<  and  some  identifier  that  you  choose  to  begin  the  heredoc.  In  this  example  we  chose  TEST  as  our  
identifier.  
• Repeat   the   identifier   followed   by   a   semicolon   to   end   the   heredoc   string   creation.   In   this   example   that  
was  TEST;  
• The  closing  sequence  TEST;  must  occur  on  a  line  by  itself  and  cannot  be  indented!  

Another  thing  to  note  is  that  when  you  output  this  multi-­‐line  string  to  a  web  page,  it  will  not  span  multiple  lines  
because   we   did   not   have   any   <br   />   tags   contained   inside   our   string!   Here   is   the   output   made   from   the   code  
above.  

Output:  
'KCC  -­‐  Unlock  your  potential  
 
 
The  Concatenation  Operator  
There  is  only  one  string  operator  in  PHP.  The  concatenation  operator  (.)  is  used  to  put  two  string  values  
[Link]  concatenate  two  variables  together,  use  the  dot  (.)  operator:  
  [Link]  -­‐  9  
 
<?php  
$txt1="Hello  World";  
$txt2="1234";  
echo  $txt1  .  "  "  .  $txt2;  
?>  
If  we  look  at  the  code  above  you  see  that  we  used  the  concatenation  operator  two  times.  This  is  because  we  had  
to   insert   a   third   string.   Between   the   two   string   variables   we   added   a   string   with   a   single   character,   an   empty  
space,  to  separate  the  two  variables.  
 
The  output  of  the  code  will  be:  
Hello  World  1234  
 
Using  the  strlen()  function  
The  strlen()  function  is  used  to  find  the  length  of  a  string.  Let's  find  the  length  of  our  string  "Hello  world!"  
<?php  
echo  strlen("Hello  world!");  
?>  
The  output  of  the  code  above  will  be:  
12  
 
The  length  of  a  string  is  often  used  in  loops  or  other  functions,  when  it  is  important  to  know  when  the  string  ends.  
(i.e.  in  a  loop,  we  would  want  to  stop  the  loop  after  the  last  character  in  the  string)  
 
Using  the  strpos()  function  
• The  strpos()  function  is  used  to  search  for  a  string  or  character  within  a  string.  
• If  a  match  is  found  in  the  string,  this  function  will  return  the  position  of  the  first  match.  
• If  no  match  is  found,  it  will  return  FALSE.  
Let's  see  if  we  can  find  the  string  "world"  in  our  string:  
<?php  
echo  strpos("Hello  world!","world");  
?>  
The  output  of  the  code  above  will  be:  
6  
 
As  you  see  the  position  of  the  string  "world"  in  our  string  is  position  6.  The  reason  that  it  is  6,  and  not  7,  is  that  
the  first  position  in  the  string  is  0,  and  not  1.  
 
Operators  

In  all  programming  languages,  operators  are  used  to  manipulate  or  perform  operations  on  variables  and  values.  
We  have  already  seen  the  string  concatenation  operator  "."  and  the  assignment  operator  "="  in  pretty  much  every  
PHP  example  so  far.  

There  are  many  operators  used  in  PHP,  so  we  have  separated  them  into  the  following  categories  to  make  it  easier  
to  learn  them  all.  

• Assignment  Operators  
• Arithmetic  Operators  
• Comparison  Operators  

  [Link]  -­‐  10  


 
• String  Operators  
• Combination  Arithmetic  &  Assignment  Operators  

The  assignment  operator  =  is  used  to  assign  values  to  variables  in  PHP.  The  arithmetic  operator  +  is  used  to  add  
values  together.  

 
Arithmetic  Operators  

The  table  below  lists  the  arithmetic  operators  in  PHP:  

Operator   Name   Description   Example   Result  


x  +  y   Addition   Sum  of  x  and  y   2  +  2   4  
x  -­‐  y   Subtraction   Difference  of  x  and  y   5  -­‐  2   3  
x  *  y   Multiplication   Product  of  x  and  y   5  *  2   10  
x  /  y   Division   Quotient  of  x  and  y   15  /  5   3  
x  %  y   Modulus   Remainder  of  x  divided  by  y   5  %  2   1  
10  %  8   2  
10  %  2   0  
-­‐  x   Negation   Opposite  of  x   -­‐  2      
a  .  b   Concatenation   Concatenate  two  strings   "Hi"  .  "Ha"   HiHa  

Assignment  Operators  

The  basic  assignment  operator  in  PHP  is  "=".  It  means  that  the  left  operand  gets  set  to  the  value  of  the  expression  
on  the  right.  That  is,  the  value  of  "$x  =  5"  is  5.  

Assignment   Same  as...   Description  


x  =  y   x  =  y   The  left  operand  gets  set  to  the  value  of  the  expression  on  the  right  
x  +=  y   x  =  x  +  y   Addition  
x  -­‐=  y   x  =  x  -­‐  y   Subtraction  
x  *=  y   x  =  x  *  y   Multiplication  
x  /=  y   x  =  x  /  y   Division  
x  %=  y   x  =  x  %  y   Modulus  
a  .=  b   a  =  a  .  b   Concatenate  two  strings  

Incrementing/Decrementing  Operators  

Operator   Name   Description  


++  x   Pre-­‐increment   Increments  x  by  one,  then  returns  x  
x  ++   Post-­‐increment   Returns  x,  then  increments  x  by  one  
-­‐-­‐  x   Pre-­‐decrement   Decrements  x  by  one,  then  returns  x  
x  -­‐-­‐   Post-­‐decrement   Returns  x,  then  decrements  x  by  one  

  [Link]  -­‐  11  


 
 

   

  [Link]  -­‐  12  


 
Comparison  Operators  

Comparison  operators  allows  you  to  compare  two  values:  

Operator   Name   Description   Example  


x  ==  y   Equal   True  if  x  is  equal  to  y   5==8  returns  false  
x  ===  y   Identical   True  if  x  is  equal  to  y,  and  they  are  of   5==="5"  returns  false  
same  type  
x  !=  y   Not  equal   True  if  x  is  not  equal  to  y   5!=8  returns  true  
x  <>  y   Not  equal   True  if  x  is  not  equal  to  y   5<>8  returns  true  
x  !==  y   Not  identical   True  if  x  is  not  equal  to  y,  or  they  are  not   5!=="5"  returns  true  
of  same  type  
x  >  y   Greater  than   True  if  x  is  greater  than  y   5>8  returns  false  
x  <  y   Less  than   True  if  x  is  less  than  y   5<8  returns  true  
x  >=  y   Greater  than  or  equal  to   True  if  x  is  greater  than  or  equal  to  y   5>=8  returns  false  

x  <=  y   Less  than  or  equal  to   True  if  x  is  less  than  or  equal  to  y   5<=8  returns  true  

Logical  Operators  

Operator   Name   Description   Example  


x  and  y   And   True  if  both  x  and  y  are  true   x=6  
y=3    
(x  <  10  and  y  >  1)  returns  true  
x  or  y   Or   True  if  either  or  both  x  and  y  are  true   x=6  
y=3    
(x==6  or  y==5)  returns  true  
x  xor  y   Xor   True  if  either  x  or  y  is  true,  but  not  both   x=6  
y=3    
(x==6  xor  y==3)  returns  false  
x  &&  y   And   True  if  both  x  and  y  are  true   x=6  
y=3  
(x  <  10  &&  y  >  1)  returns  true  
x  ||  y   Or   True  if  either  or  both  x  and  y  are  true   x=6  
y=3  
(x==5  ||  y==5)  returns  false  
!  x   Not   True  if  x  is  not  true   x=6  
y=3  
!(x==y)  returns  true  

Array  Operators  

Operator   Name   Description  


x  +  y   Union   Union  of  x  and  y  

  [Link]  -­‐  13  


 
x  ==  y   Equality   True  if  x  and  y  have  the  same  key/value  pairs  
x  ===  y   Identity   True  if  x  and  y  have  the  same  key/value  pairs  in  the  same  order  and  of  the  same  
types  
x  !=  y   Inequality   True  if  x  is  not  equal  to  y  
x  <>  y   Inequality   True  if  x  is  not  equal  to  y  
x  !==  y   Non-­‐identity   True  if  x  is  not  identical  to  y  
 

Conditional  Statements  

In  PHP  we  have  the  following  conditional  statements:  

• if  statement  -­‐  use  this  statement  to  execute  some  code  only  if  a  specified  condition  is  true  
• if...else  statement  -­‐  use  this  statement  to  execute  some  code  if  a  condition  is  true  and  another  code  if  the  
condition  is  false  
• if...elseif....else  statement  -­‐  use  this  statement  to  select  one  of  several  blocks  of  code  to  be  executed  
• switch  statement  -­‐  use  this  statement  to  select  one  of  many  blocks  of  code  to  be  executed  

 
The  if  Statement  

Use  the  if  statement  to  execute  some  code  only  if  a  specified  condition  is  true.  

Syntax  
if  (condition)  code  to  be  executed  if  condition  is  true;  

The  following  example  will  output  "Have  a  nice  weekend!"  if  the  current  day  is  Friday:  

<html>  
<body>  
 
<?php  
$d=date("D");  
if  ($d=="Fri")  echo  "Have  a  nice  weekend!";  
?>  
 
</body>  
</html>  

Note  that  there  is  no  ‘else’  in  this  syntax.  The  code  is  executed  only  if  the  specified  condition  is  true.  

 
The  if...else  Statement  

Use  the  if...  else  statement  to  execute  some  code  if  a  condition  is  true  and  another  code  if  a  condition  is  false.  

  [Link]  -­‐  14  


 
Syntax  
if  (condition)  
   {  
   code  to  be  executed  if  condition  is  true;  
   }  
else  
   {  
   code  to  be  executed  if  condition  is  false;  
   }  

Example  

The  following  example  will  output  "Have  a  nice  weekend!"  if  the  current  day  is  Friday,  otherwise  it  will  output  
"Have  a  nice  day!"  

<html>  
<body>  
 
<?php  
$d=date("D");  
if  ($d=="Fri")  
   {  
   echo  "Have  a  nice  weekend!";  
   }  
else  
   {  
   echo  "Have  a  nice  day!";  
   }  
?>  
 
</body>  
</html>  
 
The  if...  elseif...  else  Statement  

Use  the  if...  elseif…  else  statement  to  select  one  of  several  blocks  of  code  to  be  executed.  

Syntax  
if  (condition)  
   {  
   code  to  be  executed  if  condition  is  true;  
   }  
elseif  (condition)  
   {  
   code  to  be  executed  if  condition  is  true;  
   }  
else  
   {  

  [Link]  -­‐  15  


 
   code  to  be  executed  if  condition  is  false;  
   }  

Example  

The  following  example  will  output  "Have  a  nice  weekend!"  if  the  current  day  is  Friday,  and  "Have  a  nice  Sunday!"  
if  the  current  day  is  Sunday.  Otherwise  it  will  output  "Have  a  nice  day!":  

<html>  
<body>  
 
<?php  
$d=date("D");  
if  ($d=="Fri")  
   {  
   echo  "Have  a  nice  weekend!";  
   }  
elseif  ($d=="Sun")  
   {  
   echo  "Have  a  nice  Sunday!";  
   }  
else  
   {  
   echo  "Have  a  nice  day!";  
   }  
?>  
 
</body>  
</html>  
 

The  PHP  Switch  Statement  

Use  the  switch  statement  to  select  one  of  many  blocks  of  code  to  be  executed.  

Syntax  
switch  (n)  
{  
case  label1:  
   code  to  be  executed  if  n=label1;  
   break;  
case  label2:  
   code  to  be  executed  if  n=label2;  
   break;  
default:  
   code  to  be  executed  if  n  is  different  from  both  label1  and  label2;  
}  

This  is  how  it  works:    

  [Link]  -­‐  16  


 
First  we  have  a  single  expression  n  (most  often  a  variable),  that  is  evaluated  once.  The  value  of  the  expression  is  
then  compared  with  the  values  for  each  case  in  the  structure.  If  there  is  a  match,  the  block  of  code  associated  with  
that  case  is  executed.  Use  break  to  prevent  the  code  from  running  into  the  next  case  automatically.  The  default  
statement  is  used  if  no  match  is  found.  

Example  
<html>  
<body>  
 
<?php  
$x=1;  
switch  ($x)  
{  
case  1:  
   echo  "Number  1";  
   break;  
case  2:  
   echo  "Number  2";  
   break;  
case  3:  
   echo  "Number  3";  
   break;  
default:  
   echo  "No  number  between  1  and  3";  
}  
?>  
 
</body>  
</html>  
 
 

Loops  execute  a  block  of  code  a  specified  number  of  times,  or  while  a  specified  condition  is  true.  

 
PHP  Loops  

Often  when  you  write  code,  you  want  the  same  block  of  code  to  run  over  and  over  again  in  a  row.  Instead  of  
adding  several  almost  equal  lines  in  a  script  we  can  use  loops  to  perform  a  task  like  this.  

In  PHP,  we  have  the  following  looping  statements:  

• while  -­‐  loops  through  a  block  of  code  while  a  specified  condition  is  true  
• do...while  -­‐  loops  through  a  block  of  code  once,  and  then  repeats  the  loop  as  long  as  a  specified  condition  
is  true  
• for  -­‐  loops  through  a  block  of  code  a  specified  number  of  times  
• foreach  -­‐  loops  through  a  block  of  code  for  each  element  in  an  array  

  [Link]  -­‐  17  


 
The  while  Loop  

The  while  loop  executes  a  block  of  code  while  a  condition  is  true.  

Syntax  
while  (condition)  
   {  
   code  to  be  executed;  
   }  

Example  

The  example  below  first  sets  a  variable  i  to  1  ($i=1;).  

Then,  the  while  loop  will  continue  to  run  as  long  as  i  is  less  than,  or  equal  to  5.  i  will  increase  by  1  each  time  the  
loop  runs:  

<html>  
<body>  
 
<?php  
$i=1;  
while($i<=5)  
   {  
   echo  "The  number  is  "  .  $i  .  "<br>";  
   $i++;  
   }  
?>  
 
</body>  
</html>  

Output:  

The  number  is  1  


The  number  is  2  
The  number  is  3  
The  number  is  4  
The  number  is  5  
 
 
The  do...while  Statement  

The  do...while  statement  will  always  execute  the  block  of  code  once,  it  will  then  check  the  condition,  and  repeat  
the  loop  while  the  condition  is  true.  

Syntax  
do  
   {  

  [Link]  -­‐  18  


 
   code  to  be  executed;  
   }  
while  (condition);  

Example  

The  example  below  first  sets  a  variable  i  to  1  ($i=1;).  

Then,  it  starts  the  do...while  loop.  The  loop  will  increment  the  variable  i  with  1,  and  then  write  some  output.  Then  
the  condition  is  checked  (is  i  less  than,  or  equal  to  5),  and  the  loop  will  continue  to  run  as  long  as  i  is  less  than,  or  
equal  to  5:  

<html>  
<body>  
 
<?php  
$i=1;  
do  
   {  
   $i++;  
   echo  "The  number  is  "  .  $i  .  "<br>";  
   }  
while  ($i<=5);  
?>  
 
</body>  
</html>  

Output:  

The  number  is  2  


The  number  is  3  
The  number  is  4  
The  number  is  5  
The  number  is  6  
 

The  for  Loop  

The  for  loop  is  used  when  you  know  in  advance  how  many  times  the  script  should  run.  

Syntax  
for  (init;  condition;  increment)  
   {  
   code  to  be  executed;  
   }  

Parameters:  

• init:  Mostly  used  to  set  a  counter  (but  can  be  any  code  to  be  executed  once  at  the  beginning  of  the  loop)  

  [Link]  -­‐  19  


 
• condition:  Evaluated  for  each  loop  iteration.  If  it  evaluates  to  TRUE,  the  loop  continues.  If  it  evaluates  to  
FALSE,  the  loop  ends.  
• increment:  Mostly  used  to  increment  a  counter  (but  can  be  any  code  to  be  executed  at  the  end  of  the  
iteration)  

Note:  The  init  and  increment  parameters  above  can  be  empty  or  have  multiple  expressions  (separated  by  
commas).  

Example  

The  example  below  defines  a  loop  that  starts  with  i=1.  The  loop  will  continue  to  run  as  long  as  the  variable  i  is  
less  than,  or  equal  to  5.  The  variable  i  will  increase  by  1  each  time  the  loop  runs:  

<html>  
<body>  
 
<?php  
for  ($i=1;  $i<=5;  $i++)  
   {  
   echo  "The  number  is  "  .  $i  .  "<br>";  
   }  
?>  
 
</body>  
</html>  

Output:  

The  number  is  1  


The  number  is  2  
The  number  is  3  
The  number  is  4  
The  number  is  5  
 
 
The  foreach  Loop  

The  foreach  loop  is  used  to  loop  through  arrays.  

Syntax  
foreach  ($array  as  $value)  
   {  
   code  to  be  executed;  
   }  

For  every  loop  iteration,  the  value  of  the  current  array  element  is  assigned  to  $value  (and  the  array  pointer  is  
moved  by  one)  -­‐  so  on  the  next  loop  iteration,  you'll  be  looking  at  the  next  array  value.  

  [Link]  -­‐  20  


 
Example  

The  following  example  demonstrates  a  loop  that  will  print  the  values  of  the  given  array:  

<html>  
<body>  
 
<?php  
$x=array("one","two","three");  
foreach  ($x  as  $value)  
   {  
   echo  $value  .  "<br>";  
   }  
?>  
 
</body>  
</html>  

Output:  

one  
two  
three  
 

An  array  stores  multiple  values  in  one  single  variable.  

 
Array  

Like arrays in other languages, PHP arrays allow you to store multiple values in a single variable and
operate on them as a set.  

A  variable  is  a  storage  area  holding  a  number  or  text.  The  problem  is,  a  variable  will  hold  only  one  value.  An  array  
is  a  special  variable,  which  can  store  multiple  values  in  one  single  variable.  

If  you  have  a  list  of  items  (a  list  of  car  names,  for  example),  storing  the  cars  in  single  variables  could  look  like  this:  

$cars1="Saab";  
$cars2="Volvo";  
$cars3="BMW";  

However,  what  if  you  want  to  loop  through  the  cars  and  find  a  specific  one?  And  what  if  you  had  not  3  cars,  but  
300?  

The  best  solution  here  is  to  use  an  array!  

  [Link]  -­‐  21  


 
An  array  can  hold  all  your  variable  values  under  a  single  name.  And  you  can  access  the  values  by  referring  to  the  
array  name.  

Each  element  in  the  array  has  its  own  index  so  that  it  can  be  easily  accessed.  

In  PHP,  there  are  three  kind  of  arrays:  

• Numeric  array  (Enumerated  Arrays)  -­‐  An  array  with  a  numeric  index  
• Associative  array  -­‐  An  array  where  each  ID  key  is  associated  with  a  value  
• Multidimensional  array  -­‐  An  array  containing  one  or  more  arrays  

 
Numeric  Arrays  (Enumerated  Arrays)  

A  numeric  array  stores  each  array  element  with  a  numeric  index.  

There  are  two  methods  to  create  a  numeric  array.  

1.  In  the  following  example  the  index  are  automatically  assigned  (the  index  starts  at  0):  

$cars=array("Saab","Volvo","BMW","Toyota");  

2.  In  the  following  example  we  assign  the  index  manually:  

$cars[0]="Saab";  
$cars[1]="Volvo";  
$cars[2]="BMW";  
$cars[3]="Toyota";  

Example  

In  the  following  example  you  access  the  variable  values  by  referring  to  the  array  name  and  index:  

<?php  
$cars[0]="Saab";  
$cars[1]="Volvo";  
$cars[2]="BMW";  
$cars[3]="Toyota";    
 
echo  $cars[0]  .  "  and  "  .  $cars[1]  .  "  are  Swedish  cars.";  
?>  

The  code  above  will  output:  

Saab  and  Volvo  are  Swedish  cars.  


 
 

  [Link]  -­‐  22  


 
Associative  Arrays  

An  associative  array,  each  ID  key  is  associated  with  a  value.  

When  storing  data  about  specific  named  values,  a  numerical  array  is  not  always  the  best  way  to  do  it.  

With  associative  arrays  we  can  use  the  values  as  keys  and  assign  values  to  them.  

Example  1  

In  this  example  we  use  an  array  to  assign  ages  to  the  different  persons:  

$ages  =  array("Peter"=>32,  "Quagmire"=>30,  "Joe"=>34);  

Example  2  

This  example  is  the  same  as  example  1,  but  shows  a  different  way  of  creating  the  array:  

$ages['Peter']  =  "32";  
$ages['Quagmire']  =  "30";  
$ages['Joe']  =  "34";  

The  ID  keys  can  be  used  in  a  script:  

<?php  
$ages['Peter']  =  "32";  
$ages['Quagmire']  =  "30";  
$ages['Joe']  =  "34";  
 
echo  "Peter  is  "  .  $ages['Peter']  .  "  years  old.";  
?>  

The  code  above  will  output:  

Peter  is  32  years  old.  


 
 
Multidimensional  Arrays  

In  a  multidimensional  array,  each  element  in  the  main  array  can  also  be  an  array.  And  each  element  in  the  sub-­‐
array  can  be  an  array,  and  so  on.  

Example  

In  this  example  we  create  a  multidimensional  array,  with  automatically  assigned  ID  keys:  

$families  =  array  
   (  
   "Griffin"=>array  
   (  
  [Link]  -­‐  23  
 
   "Peter",  
   "Lois",  
   "Megan"  
   ),  
   "Quagmire"=>array  
   (  
   "Glenn"  
   ),  
   "Brown"=>array  
   (  
   "Cleveland",  
   "Loretta",  
   "Junior"  
   )  
   );  

The  array  above  would  look  like  this  if  written  to  the  output:  

Array  
(  
[Griffin]  =>  Array  
   (  
   [0]  =>  Peter  
   [1]  =>  Lois  
   [2]  =>  Megan  
   )  
[Quagmire]  =>  Array  
   (  
   [0]  =>  Glenn  
   )  
[Brown]  =>  Array  
   (  
   [0]  =>  Cleveland  
   [1]  =>  Loretta  
   [2]  =>  Junior  
   )  
)  

Example  2  

Lets  try  displaying  a  single  value  from  the  array  above:  

echo  "Is  "  .  $families['Griffin'][2]  .  "  a  part  of  the  Griffin  family?";  

The  code  above  will  output:  

Is  Megan  a  part  of  the  Griffin  family?  


 
 
Array  functions  
  [Link]  -­‐  24  
 
PHP offers an extensive array manipulation toolkit—over 60 functions—that lets you process arrays in almost any
way imaginable including reversing them, extracting subsets, comparing and sorting, recursively processing, and
searching them for specific values.

Function   Explanation   Example  

This  function  returns  the  


number  of  elements  in  an   Code:  
array.   $data  =  array("red",  "green",  "blue");  
 
Use  this  function  to  find  out   echo  "Array  has  "  .  sizeof($data)  .  "  
sizeof($arr)  
how  many  elements  an  array   elements";  
contains;  this  information  is   ?>  
most  commonly  used  to    
initialize  a  loop  counter   Output:  
when  processing  the  array.   Array  has  3  elements  

Code:  
This  function  accepts  a  PHP   $data  =  array("hero"  =>  "Holmes",  
array  and  returns  a  new   "villain"  =>  "Moriarty");  
array  containing  only  its   print_r(array_values($data));  
values  (not  its  keys).  Its   ?>  
counterpart  is  the    
array_values($arr)  
array_keys()  function.   Output:  
Array  
Use  this  function  to  retrieve  
(  
all  the  values  from  an  
[0]  =>  Holmes  
associative  array.  
[1]  =>  Moriarty  
)  
Code:  
This  function  accepts  a  PHP   $data  =  array("hero"  =>  "Holmes",  
array  and  returns  a  new   "villain"  =>  "Moriarty");  
array  containing  only  its   print_r(array_keys($data));  
keys  (not  its  values).  Its   ?>  
counterpart  is  the    
array_keys($arr)  
array_values()  function.   Output:  
Array  
Use  this  function  to  retrieve  
(  
all  the  keys  from  an  
[0]  =>  hero  
associative  array.  
[1]  =>  villain  
)  
Code:  
$data  =  array("Donald",  "Jim",  "Tom");  
array_pop($data);  
print_r($data);  
This  function  removes  an   ?>  
array_pop($arr)   element  from  the  end  of  an    
array.   Output:  
Array  
(  
[0]  =>  Donald  
[1]  =>  Jim  
)  

  [Link]  -­‐  25  


 
Code:  
$data  =  array("Donald",  "Jim",  "Tom");  
array_push($data,  "Harry");  
print_r($data);  
?>  
This  function  adds  an    
array_push($arr,  $val)   element  to  the  end  of  an   Output:  
array.   Array  
(  
[0]  =>  Donald  
[1]  =>  Jim  
[2]  =>  Tom  
[3]  =>  Harry  
)  
Code:  
$data  =  array("Donald",  "Jim",  "Tom");  
array_shift($data);  
print_r($data);  
This  function  removes  an   ?>  
array_shift($arr)   element  from  the  beginning    
of  an  array.   Output:  
Array  
(  
[0]  =>  Jim  
[1]  =>  Tom  
)  
Code:  
$data  =  array("Donald",  "Jim",  "Tom");  
array_unshift($data,  "Sarah");  
print_r($data);  
?>  
This  function  adds  an    
array_unshift($arr,  $val)   element  to  the  beginning  of   Output:  
an  array.   Array  
(  
[0]  =>  Sarah  
[1]  =>  Donald  
[2]  =>  Jim  
[3]  =>  Tom  
)  
Code:  
This  function  is  most  often   $data  =  array("hero"  =>  "Holmes",  
used  to  iteratively  traverse   "villain"  =>  "Moriarty");  
an  array.  Each  time  each()  is   while  (list($key,  $value)  =  each($data))  {  
called,  it  returns  the  current   echo  "$key:  $value  \n";  
each($arr)  
key-­‐value  pair  and  moves   }  
the  array  cursor  forward  one   ?>  
element.  This  makes  it  most    
suitable  for  use  in  a  loop.   Output:  
hero:  Holmes    
villain:  Moriarty  

sort($arr)   This  function  sorts  the   Code:  


elements  of  an  array  in   $data  =  array("g",  "t",  "a",  "s");  

  [Link]  -­‐  26  


 
ascending  order.  String   sort($data);  
values  will  be  arranged  in   print_r($data);  
ascending  alphabetical   ?>  
order.    
Output:  
Note:  Other  sorting  functions   Array  
include  asort(),  arsort(),   (  
ksort(),  krsort()  and  rsort().   [0]  =>  a  
[1]  =>  g  
[2]  =>  s  
[3]  =>  t  
)  
Code:  
The  function  exchanges  the   $data  =  array("a"  =>  "apple",  "b"  =>  
keys  and  values  of  a  PHP   "ball");  
associative  array.   print_r(array_flip($data));  
?>  
Use  this  function  if  you  have  
array_flip($arr)    
a  tabular  (rows  and  
Output:  
columns)  structure  in  an  
Array  
array,  and  you  want  to  
(  
interchange  the  rows  and  
[apple]  =>  a  
columns.  
[ball]  =>  b  
)  

The  function  reverses  the   Code:  


order  of  elements  in  an   $data  =  array(10,  20,  25,  60);  
array.   print_r(array_reverse($data));  
?>  
Use  this  function  to  re-­‐order    
a  sorted  list  of  values  in   Output:  
array_reverse($arr)  
reverse  for  easier   Array  
processing—for  example,   (  
when  you're  trying  to  begin   [0]  =>  60  
with  the  minimum  or   [1]  =>  25  
maximum  of  a  set  of  ordered   [2]  =>  20  
values.   [3]  =>  10  
)  
Code:  
This  function  merges  two  or   $data1  =  array("cat",  "goat");  
more  arrays  to  create  a   $data2  =  array("dog",  "cow");  
single  composite  array.  Key   print_r(array_merge($data1,  $data2));  
collisions  are  resolved  in   ?>  
favor  of  the  latest  entry.    
array_merge($arr)   Output:  
Use  this  function  when  you  
Array  
need  to  combine  data  from  
(  
two  or  more  arrays  into  a  
[0]  =>  cat  
single  structure—for  
[1]  =>  goat  
example,  records  from  two  
[2]  =>  dog  
different  SQL  queries.  
[3]  =>  cow  
)  

array_rand($arr)   This  function  selects  one  or   Code:  


more  random  elements  from   $data  =  array("white",  "black",  "red");  

  [Link]  -­‐  27  


 
an  array.   echo  "Today's  color  is  "  .  
$data[array_rand($data)];  
Use  this  function  when  you   ?>  
need  to  randomly  select    
from  a  collection  of  discrete   Output:  
values—for  example,  picking   Today's  color  is  red  
a  random  color  from  a  list.  

This  function  searches  the  


values  in  an  array  for  a  
match  to  the  search  term,   Code:  
and  returns  the   $data  =  array("blue"  =>  "#0000cc",  
corresponding  key  if  found.   "black"  =>  "#000000",  "green"  =>  
If  more  than  one  match   "#00ff00");  
array_search($search,  $arr)   exists,  the  key  of  the  first   echo  "Found  "  .  array_search("#0000cc",  
matching  value  is  returned.   $data);  
?>  
Use  this  function  to  scan  a    
set  of  index-­‐value  pairs  for   Output:  
matches,  and  return  the   Found  blue  
matching  index.  

This  function  is  useful  to  


extract  a  subset  of  the   Code:  
elements  of  an  array,  as   $data  =  array("vanilla",  "strawberry",  
another  array.  Extracting   "mango",  "peaches");  
begins  from  array  offset   print_r(array_slice($data,  1,  2));  
$offset  and  continues  until   ?>  
array_slice($arr,  $offset,   the  array  slice  is  $length    
$length)   elements  long.   Output:  
Array  
Use  this  function  to  break  a  
(  
larger  array  into  smaller  
[0]  =>  strawberry  
ones—for  example,  when  
[1]  =>  mango  
segmenting  an  array  by  size  
)  
("chunking")  or  type  of  data.  

Code:  
$data  =  array(1,1,4,6,7,4);  
This  function  strips  an  array   print_r(array_unique($data));  
of  duplicate  values.   ?>  
 
Use  this  function  when  you  
Output:  
array_unique($data)   need  to  remove  non-­‐unique  
Array  
elements  from  an  array—for  
(  
example,  when  creating  an  
[0]  =>  1  
array  to  hold  values  for  a  
[3]  =>  6  
table's  primary  key.  
[4]  =>  7  
[5]  =>  4  
)  
This  function  "walks"   Code:  
array_walk($arr,  $func)   through  an  array,  applying  a   function  reduceBy10(&$val,  $key)  {  
user-­‐defined  function  to   $val  -­‐=  $val  *  0.1;  
every  element.  It  returns  the   }  

  [Link]  -­‐  28  


 
changed  array.    
$data  =  array(10,20,30,40);  
Use  this  function  if  you  need   array_walk($data,  'reduceBy10');  
to  perform  custom   print_r($data);  
processing  on  every  element   ?>  
of  an  array—for  example,    
reducing  a  number  series  by   Output:  
10%.   Array  
(  
[0]  =>  9  
[1]  =>  18  
[2]  =>  27  
[3]  =>  36  
)  

 
 
 
 
 
PHP  Functions  

A  function  is  just  a  name  we  give  to  a  block  of  code  that  can  be  executed  whenever  we  need  it.  This  might  not  
seem  like  that  big  of  an  idea,  but  believe  me,  when  you  understand  and  use  functions  you  will  be  able  to  save  a  
ton  of  time  and  write  code  that  is  much  more  readable!  

For  example,  you  might  have  a  company  motto  that  you  have  to  display  at  least  once  on  every  webpage.  If  
you  don't,  then  you  get  fired!  Well,  being  the  savvy  PHP  programmer  you  are,  you  think  to  yourself,  "this  
sounds  like  a  situation  where  I  might  need  functions."  

Tip:  Although  functions  are  often  thought  of  as  an  advanced  topic  for  beginning  programmers  to  learn,  if  you  take  
it   slow   and   stick   with   it,   functions   can   be   just   minor   speed   bump   in   your   programming   career.   So   don't   give   up   if  
functions  confuse  you  at  first!  

To  keep  the  script  from  being  executed  when  the  page  loads,  you  can  put  it  into  a  function.  A  function  will  be  
executed  by  a  call  to  the  function.  You  may  call  a  function  from  anywhere  within  a  page.  

+  PHP  Built-­‐in  Functions  

• PHP  Array  Functions  


• PHP  Calendar  Functions  
• PHP  Date  &  Time  Functions  
• PHP  Error  Handling  Functions  
• PHP  File  System  Functions  
• PHP  MySQL  Functions  
• PHP  String  Functions  

 
+  PHP  User  Defined  Functions  
Create  a  PHP  Function  

A  function  will  be  executed  by  a  call  to  the  function.  


  [Link]  -­‐  29  
 
Syntax  
function  functionName()  
{  
code  to  be  executed;  
}  

PHP  function  guidelines:  

• Give  the  function  a  name  that  reflects  what  the  function  does  
• The  function  name  can  start  with  a  letter  or  underscore  (not  a  number)  

Example  

A  simple  function  that  writes  my  name  when  it  is  called:  

<html>  
<body>  
 
<?php  
function  writeName()  
{  
echo  "Kai  Jim  Refsnes";  
}  
 
echo  "My  name  is  ";  
writeName();  
?>  
 
</body>  
</html>  

Output:  

My  name  is  Kai  Jim  Refsnes  


 
 
PHP  Functions  -­‐  Adding  parameters  

To  add  more  functionality  to  a  function,  we  can  add  parameters.  A  parameter  is  just  like  a  variable.  Parameters  
are  specified  after  the  function  name,  inside  the  parentheses.  

Example  1  

The  following  example  will  write  different  first  names,  but  equal  last  name:  

<html>  
<body>  
 
<?php  
function  writeName($fname)  
{  
echo  $fname  .  "  Refsnes.<br>";  
}  
 
echo  "My  name  is  ";  
  [Link]  -­‐  30  
 
writeName("Kai  Jim");  
echo  "My  sister's  name  is  ";  
writeName("Hege");  
echo  "My  brother's  name  is  ";  
writeName("Stale");  
?>  
 
</body>  
</html>  

Output:  

My  name  is  Kai  Jim  Refsnes.  


My  sister's  name  is  Hege  Refsnes.  
My  brother's  name  is  Stale  Refsnes.  

Example  2  

The  following  function  has  two  parameters:  

<html>  
<body>  
 
<?php  
function  writeName($fname,$punctuation)  
{  
echo  $fname  .  "  Refsnes"  .  $punctuation  .  "<br>";  
}  
 
echo  "My  name  is  ";  
writeName("Kai  Jim",".");  
echo  "My  sister's  name  is  ";  
writeName("Hege","!");  
echo  "My  brother's  name  is  ";  
writeName("Ståle","?");  
?>  
 
</body>  
</html>  

Output:  

My  name  is  Kai  Jim  Refsnes.  


My  sister's  name  is  Hege  Refsnes!  
My  brother's  name  is  Ståle  Refsnes?  
   
 
PHP  Functions  -­‐  Return  values  

To  let  a  function  return  a  value,  use  the  return  statement.  

Example  
<html>  
<body>  
  [Link]  -­‐  31  
 
 
<?php  
function  add($x,$y)  
{  
$total=$x+$y;  
return  $total;  
}  
 
echo  "1  +  16  =  "  .  add(1,16);  
?>  
 
</body>  
</html>  

Output:  

1  +  16  =  17  
   

  [Link]  -­‐  32  


 
PHP  String  Functions  

substr()  

This  function  returns  the  part  of  the  string  as  an  output.  

Syntax  :  
substr(<string>,<start>,[<length>]);  
 
Explanation  :  

String  :  It  is  mandatory  parameter.  The  string  from  which  the  part  is  to  be  extracted  is  mentioned  here.  

Start  :  The  start  in  the  string  from  which  the  characters  are  to  be  extracted  

• Positive  number  –  Start  at  a  specified  position  in  the  string  


• Negative  number  –  Start  at  a  specified  position  from  the  end  of  the  string  
• 0  –  Start  at  the  first  character  in  string  

Length  :  It  is  an  optional  parameter.  It  specifies  the  length  of  the  string  which  is  to  be  extracted.  

• Positive  number  –  The  length  to  be  returned  from  the  start  parameter  
• Negative  number  –  The  length  to  be  returned  from  the  end  of  the  string  
Example  1:  
<?php  echo  substr("Hello  world",6);  ?>  //Returns  world  
 
Example  2  :  
<?php  echo  substr("Hello  world",6,4);  ?>  //  Returns  worl  
 
 
Example  3  :  
<?php  echo  substr("Hello  world",  -­‐1);  ?>  //  Returns    d  
 
 
Example  4:  
<?php  echo  substr("Hello  world",  -­‐3,  -­‐1);  ?>  //  Returns  rl  
 
 
strlen()  

This  function  returns  the  length  of  the  string  

Syntax  :  
strlen(<string>);  
 
Explanation:  

String  :  It  is  mandatory  field.  The  string  whose  length  is  to  be  found  out  is  mentioned  here.  

Example  1:  
<?php  echo  strlen("Hello  world");    ?>  //  Returns  11  
 
 
trim()  

This  function  removes  the  whitespaces  from  both  start  and  the  end  of  the  string.  

Syntax  :  
trim(<string>);  
 
  [Link]  -­‐  33  
 
Explanation  :  

String  :  It  is  mandatory  field.  The  string  of  which  the  whitespaces  are  to  be  removed  is  passed  as  parameter.  

Example  1:  
<?php  echo  trim(  "                Hello  World        ");  ?>      
 
  Returns  Hello  World.  If  you  go  view  source  then  you  can  see  that  there  are  no  whitespaces.  
 
ltrim()  

This  function  removes  the  whitespaces  from  the  left  part  of  the  string.  

Syntax  :  
ltrim(<string>);  
 
Explanation  :  

String  :  It  is  mandatory  field.  The  string  of  which  the  whitespaces  are  to  be  removed  from  left  side  is  passed  as  
parameter.  

Example  1:  
<?php  echo  ltrim(  "                Hello  World        ");  ?>      
 
Returns  Hello  World.  If  you  go  view  source  then  you  can  see  that  there  are  no  whitespaces  on  left  side  but  there  
 
are  spaces  on  right  side.  
 
rtrim()  
This  function  removes  the  whitespaces  from  the  right  part  of  the  string.  

Syntax  :  
rtrim(<string>);  
 
Explanation  :  

String  :  It  is  mandatory  field.  The  string  of  which  the  whitespaces  are  to  be  removed  from  right  side  is  passed  as  
parameter.  

Example  1:  
<?php  echo  rtrim(  "                Hello  World        ");  ?>      
 
Returns  Hello  World.  If  you  go  view  source  then  you  can  see  that  there  are  no  whitespaces  on  right  side  but  
 
there  are  spaces  on  left  side.  
 
strtolower()  

This  function  converts  the  string  to  lower  case  

Syntax  :  
strtolower(<string>);  
 
Explanation  :  

String  :  It  is  mandatory  field.  The  string  which  is  to  be  converted  to  lower  case  is  passed  here.  

Example  1:  

  [Link]  -­‐  34  


 
<?php  echo  strtolower("HELLO  WORLD");  ?>  Returns  hello  world  
 
 
strtoupper()  

This  function  converts  the  string  to  upper  case  

Syntax  :  
strtoupper(<string>);  
Explanation  :  

String  :  It  is  mandatory  field.  The  string  which  is  to  be  converted  to  upper  case  is  passed  here.  

Example  1:  
<?php  echo  strtoupper("hello  world");  ?>  //  Returns  HELLO  WORLD  
 
str_replace()  
The  str_replace()  function  replaces  some  characters  with  some  other  characters  in  a  string.  
This  function  works  by  the  following  rules:  
• If  the  string  to  be  searched  is  an  array,  it  returns  an  array  
• If  the  string  to  be  searched  is  an  array,  find  and  replace  is  performed  with  every  array  element  
• If  both  find  and  replace  are  arrays,  and  replace  has  fewer  elements  than  find,  an  empty  string  will  be  used  as  
replace  
• If  find  is  an  array  and  replace  is  a  string,  the  replace  string  will  be  used  for  every  find  value  
Syntax  :  
str_replace(<search>,<replace>,<string/array>,[<count>]);  
 
 
Explanation  :  

Search  :  It  is  mandatory  .  The  string  or  value  to  be  searched  comes  here.  

Replace  :  It  is  mandatory.  The  string  or  value  to  be  replaced  comes  here.  

String/Array  :  It  is  mandatory.  The  string  or  array  in  which  the  value  is  to  be  found  out  comes  here.  

Count  :  It  is  optional.  It  counts  the  number  of  replacements  to  be  done.  

Example  1:  
<?php  echo  str_replace("world","Peter","Hello  world");  ?>//  Returns  Hello  Peter  
 
Example  2:  
<?php  
 
 $arr  =  array("blue","red","green","yellow");  
 
 print_r(str_replace("red","pink",$arr,$i));  
 
 echo  "Replacements:  $i";  
 
 ?>  
 
   
 
Output:  
 
   Array  
 
 (  
 
 [0]  =>  blue  
 
  [Link]  -­‐  35  
 
 [1]  =>  pink  
 
 [2]  =>  green  
 
 [3]  =>  yellow  
 
 )  
 
 Replacements:  1  
 
   
 
 strcmp()  

The  strcmp()  function  compares  two  strings.  

This  function  returns:  

• 0  –  if  the  two  strings  are  equal  


• <0  –  if  string1  is  less  than  string2  
• >0  –  if  string1  is  greater  than  string2  
 
Syntax  :  
strcmp(<string1>,<string2>);  
 
Explanation  :  

String1  :  It  is  mandatory.  The  first  string  comes  here.  

String  2  :  It  is  mandatory.  The  Second  string  comes  here.  

 
Example  1:  
<?php  echo  strcmp("Hello  world!","Hello  world!");  ?>    
 
//Returns  0  
Note:  The  strcmp()  function  is  binary  safe  and  case-­‐sensitive.  For  case  insensitive  comparison  you  can  use  
strcasecmp(<string1>,<string2>);  function.  It  is  similar  to  strcmp()  function.  
 
explode()  

This  function  breaks  the  string  into  array  on  the  basis  of  delimiter  passed.  

Syntax:  
explode(<delimeter>,<string>,[<limit>]);  
Explanation:  

Delimeter:  It  is  mandatory  field.  It  specifies  where  to  break  the  string.  

String:  It  is  mandatory.  It  specifies  the  string  to  split.  

Limit  :  It  is  optional.  It  specifies  the  maximum  number  of  array  elements  to  return.  

 
Example  1:  
<?php  
 
 $str  =  "Hello  world.  It's  a  beautiful  day.";  
 

  [Link]  -­‐  36  


 
 print_r  (explode("  ",$str));  
 
 ?>  
 
   
 
Output  :  
 
  Array  
 
 (  
 
 [0]  =>  Hello  
 
 [1]  =>  world.  
 
 [2]  =>  It's  
 
 [3]  =>  a  
 
 [4]  =>  beautiful  
 
 [5]  =>  day.  
 
 )  
 
   
 
 implode()  
This  function  join  array  elements  with  a  string  on  the  basis  of  delimiter  passed.  
Syntax:  
implode(<delim>,<array>);  
 
Explanation:  

Delimiter:  It  is  mandatory  field.  It  specifies  what  to  put  between  the  array  elements.  Default  is  “”  (an  empty  
string).  

Array:  It  is  mandatory  field.  It  specifies  the  array  to  join  to  a  string.  

Example  1:  
<?php  
 
 $arr  =  array('Hello','World!','Beautiful','Day!');  
 
 echo  implode("  ",$arr);  
 
 ?>  
 
Output:  
 
  Hello  World!  Beautiful  Day!  
 
 
 
 
   

  [Link]  -­‐  37  


 
File  Handling  
Opening  a  File  

The  fopen()  function  is  used  to  open  files  in  PHP.  The  first  parameter  of  this  function  contains  the  name  of  the  file  
to  be  opened  and  the  second  parameter  specifies  in  which  mode  the  file  should  be  opened:  

<html>  
<body>  
 
<?php  
                       $file=fopen("[Link]","r");  
?>  
 
</body>  
</html>  

The  file  may  be  opened  in  one  of  the  following  modes:  

Modes   Description  
r   Read  only.  Starts  at  the  beginning  of  the  file  
r+   Read/Write.  Starts  at  the  beginning  of  the  file  

w   Write  only.  Opens  and  clears  the  contents  of  file;  or  creates  a  new  file  if  it  
doesn't  exist  
w+   Read/Write.  Opens  and  clears  the  contents  of  file;  or  creates  a  new  file  if  it  
doesn't  exist  
a   Append.  Opens  and  writes  to  the  end  of  the  file  or  creates  a  new  file  if  it  doesn't  
exist  
a+   Read/Append.  Preserves  file  content  by  writing  to  the  end  of  the  file  
x   Write  only.  Creates  a  new  file.  Returns  FALSE  and  an  error  if  file  already  exists  
x+   Read/Write.  Creates  a  new  file.  Returns  FALSE  and  an  error  if  file  already  exists  

Note:  If  the  fopen()  function  is  unable  to  open  the  specified  file,  it  returns  0  (false).  

Example  

The  following  example  generates  a  message  if  the  fopen()  function  is  unable  to  open  the  specified  file:  

<html>  
<body>  
 
<?php  
$file=fopen("[Link]","r")  or  exit("Unable  to  open  file!");  
?>  
 

  [Link]  -­‐  38  


 
</body>  
</html>  
 
 
Closing  a  File  

The  fclose()  function  is  used  to  close  an  open  file:  

<?php  
$file  =  fopen("[Link]","r");  
 
//some  code  to  be  executed  
 
fclose($file);  
?>  
 
Check  End-­‐of-­‐file  

The  feof()  function  checks  if  the  "end-­‐of-­‐file"  (EOF)  has  been  reached.  The  feof()  function  is  useful  for  looping  
through  data  of  unknown  length.  

Note:  You  cannot  read  from  files  opened  in  w,  a,  and  x  mode!  

if  (feof($file))  echo  "End  of  file";  


 
 
Reading  a  File  Line  by  Line  

The  fgets()  function  is  used  to  read  a  single  line  from  a  file.  

Note:  After  a  call  to  this  function  the  file  pointer  has  moved  to  the  next  line.  

Example  

The  example  below  reads  a  file  line  by  line,  until  the  end  of  file  is  reached:  

<?php  
$file  =  fopen("[Link]",  "r")  or  exit("Unable  to  open  file!");  
//Output  a  line  of  the  file  until  the  end  is  reached  
while(!feof($file))  
   {  
   echo  fgets($file).  "<br>";  
   }  
fclose($file);  
?>  
 
 

  [Link]  -­‐  39  


 
Reading  a  File  Character  by  Character  

The  fgetc()  function  is  used  to  read  a  single  character  from  a  file.  

Note:  After  a  call  to  this  function  the  file  pointer  moves  to  the  next  character.  

Example  

The  example  below  reads  a  file  character  by  character,  until  the  end  of  file  is  reached:  

<?php  
$file=fopen("[Link]","r")  or  exit("Unable  to  open  file!");  
while  (!feof($file))  
   {  
   echo  fgetc($file);  
   }  
fclose($file);  
?>  
 
File  System  Functions  
{Refer:  PHP  _  FILE_SYSTEM  _  FUNCTIONS.}  
 
 

~  

  [Link]  -­‐  40  

You might also like