Applications Development and Emerging Technologies Reviewer
Applications Development and Emerging Technologies Reviewer
REVIEWER
MODULE 1 • Object-oriented support (Classes
Web Architecture, Tools, and and Objects)
Introduction to PHP – Introduction to • Native session-handling support
PHP (session)
• Encryption (encryption
AN INTRODUCTION TO PHP WEB algorithms)
PROGRAMMING • ISAPI Support (for IIS)
• Native COM/DOM (Windows
applications)
HISTORY • Native Java Support: (binding to
• 1994/1995 (PHP 1.0) java objects)
• Developed by Rasmus Lerdorf • PERL Compatible Regular
• To know how many visitors were Expressions
reading his online resume based on • New features, power, and scalability
PERL/CGI script
• Personal Home Page (PHP) • PHP 5 (July 13, 2004)
• 1997 (PHP 2.0) • Vastly improved object-oriented
• PHP is based on C rather than PERL capabilities: OOP improvement
• Personal Home Page/Form Interpreter • Try/catch exception handling
• 1998 (PHP 3.0) • Improved XML and Web Services
• 50,000 users were using PHP to support (Simple XML Support, using
enhance their Web pages SOAP)
• Developers joined Lerdorf • Native support for SQLite
• 1999 (PHP 4.0) • Installed on 19 million domains
• With core developers Zeev Suraski • 54 percent on all Apache module
and Andi Gutmans • PHP 6 (2007 not yet released)
• PHP makes the most popular scripting • Unicode Support (Native Unicode
language with more than one million user support for multilingual applications)
bases by Netcraff • Security improvements
• New language features and constructs
(64-bit type integer, foreach looping)
Practicality
- Mac OS X’s
- Cheetah
- Puma
- Jaguar
SOFTWARE REQUIREMENTS
- Leopard
- Snow Leopard
Operating System: Linux - Lion
- Tiger
- ubuntu (linux for human beings) - Panther
- Debian
- Linux Mandrake
- SUSE
- fedora
- CentOS (The Community Enterprise
Operating System)
- kubuntu
Internet browser
- Google Chrome
- Mozilla Firefox
- Internet Explorer
- Opera
- Safari
- Maxthon
- Rockmelt Database
- SeaMonkey
- Deepnet Explorer - IBM DB2
- Avant Browser - MySQL
- Microsoft SLQ Server
- SQLite
- PostgreSQL
- Oracle
Web Server
- Apache
- IIS7 (internet information services)
- NGINX Code editor
- Google Web Server (GWS)
- aptana
- eclipse
- Bluefish
- Dreamweaver
- NetBeans
- Notepad++
XAMPP / WAMP
- Web Server
Apache
- Language
Script PHP
- Database
MySQL
Code Editor
- Notepad++ / Eclipse / Netbeans /
Dreamweaver
<!--welcome.php -->
<html>
<head>
<title>My PHP</title>
</head>
<body>
<?php
echo 'Welcome to PHP';
MODULE 1
?>
Web Architecture, Tools, and
Introduction to PHP - PHP Environment </body>
<html>
XAMPP
1. Download XAMPP
http://www.apachefriends.org/en/xampp.ht
ml
2. Install XAMPP
3. Run XAMPP Control
• c:\xampp (by default)
?>
All php scripts must enclosed with
<?php … ?>(standard tag)
<?...?> (short open tag)
<script language=”php”>
…
</script> (script tag)
<%...%> (asp style tag)
OUTPUT:
PHP Variables
• Variables are used as a container for
values that can be used and manipulate
<?php – opening tag for php script PHP scripts.
; - Statement terminator
?> - closing tag for php script. • Variables in PHP must begin with a $
symbol.
Output:
Commonly Used Type Specifiers for
printf function
Type Description
%b Argument considered an integer;
presented as a binary number
%c Argument considered an integer;
presented as a character
corresponding to that ASCII
value
%d Argument considered an integer;
presented as a signed decimal
number
%f Argument considered a floating-
point number; presented as a
floating-point number
%o Argument considered an integer;
presented as an octal number //float
%s Argument considered a string; $v = 3.2475; //3.2475
presented as a string $v = 2.0; //2
%u Argument considered as an $v = 8.7e4; //87000
integer; presented as an $v =
unsigned decimal number
1.43E+10; //143E+10
%x Argument considered an integer;
presented as a lowercase
hexadecimal number
%X Argument considered an integer;
presented as an uppercase
hexadecimal number
PHP DATATYPES
//string
Datatypes $str = "Welcome to
PHP"; //Welcome to PHP
- is the generic name assigned to any data $str = "do-re-
sharing a common set of characteristics. mi"; //do-re-mi
$str =
Scalar Datatypes "$^expr%!"; //$^expr%!
$str =
- Capable of containing a single item of "123$%^789"; //123$^789
information
- (Boolean, Integer, Float (float, double
or real numbers), String)
Compound Datatypes
Compound Datatypes
Example:
<?php
//arrays
$arr_list[0] = "zero";
$arr_list[1] = "one";
$arr_list[2] = "two";
$arr_list[3] = "three";
for($i=0;
$i<count($arr_list); $i++)
echo Output:
$arr_list[$i]."<br/>";
?>
<?php Example:
//objects
class Student{ <?php
private $_name; $x = (double) 8;
function setName($name){ echo "<p>$x</p>";
$this->_name = $x = (int) 9.99;
$name; echo "<p>$x</p>";
} $str = "19.00 pesos is the
function getName(){ price";
return $this->_name; $x = (int) $str;
echo "<p>$x</p>"; echo "<p>$c</p>";
$x = (array) $str; ?>
echo "<p>$x[0]</p>";
$obj = (object) $str;
echo "<p>$obj->scalar</p>";
?>
Output:
Output:
gettype() function
PHP Type Juggling
- returns the type of the variable. Possible
Example: return values are integer, double, boolean,
string, array, object, resource, unknown
<?php types.
$a = 10; prototype:
$b = "20"; string gettype(mixed var)
$c = $a + $b;
settype() function
echo "<p>$c</p>";
- converts a given variable to a specific
$a = "100 apples";
type.
$b = "50 apples";
prototype:
$c = $a + $b; boolean settype(mixed var, string type)
echo "<p>$c apples</p>";
$a = "314e-2";
$b = 100;
$c = $a * $b;
Predefined Type Identifier Functions
is_array(), is_bool(), is_float(),
is_integer(), is_null(), is_numeric(),
is_object(), is_resource(), is_scalar(),
and is_string()
Type Functions
Example:
<?php
$x = 10; Summary
printf("Variable type: %s • PHP was developed originally by
<br>", gettype($x)); Rasmus Lerdorf
settype($x, double); • Seev Suraski and Andi Gutsman were
printf("Variable type: %s the one who contribute most in PHP
<br>", gettype($x)); development.
• PHP key categories are practicality,
if(is_integer($x)){ power, possibility, and price.
echo "Integer: • PHP is a embedded language that is
True<br/>"; commonly embedded on HTML
• PHP is a server-side scripting language
} else {
that runs its application on a Web server.
echo "Integer:
• Much of the PHP syntax were derive
False<br/>";
from C programming Language.
}
• You can integrate database easily in
PHP.
if(is_double($x)){ • Standard PHP script are enclosed by
echo "Double: tags.
True<br/>"; • Each statement in PHP must be
} else { terminated with a semi-colon (;).
echo "Double: • All variable in PHP must have a dollar
False<br/>"; ($) character before its identifier.
} • PHP variables are not explicitly
declared.
if(is_numeric($x)){ • You can use echo, print, or printf function
echo "Numeric: for outputting strings to internet browser.
True<br/>"; • You can enclose string using a pair of
} else { single quote or pair of double quotes.
echo "Numeric: • String inside a pair of single quotes
False<br/>"; interpreted as literal except for the single
} quote itself.
?> • String inside a pair of double quotes
interpreted as literal with some exception
like using dollar character.
• To explicitly display the character on the
internet browser use backslash (\)
character like \$, \’, \” and etc.
• Datatypes in PHP can be categorized as
scalar or compound datatypes.
• You can explicitly change the type of a • PHP can collect form data
variable in PHP. • PHP can send and receive cookies
• PHP support some predefined type • PHP can add, delete, modify data in your
function that can be used in manipulating database
type variables. • PHP can be used to control user-access
• PHP can encrypt data
SUPPLEMENTARY • With PHP you are not limited to output
HTML. You can output images, PDF files,
PHP INTRODUCTION and even Flash movies. You can also
output any text, such as XHTML and XML.
• PHP code is executed on the server.
Why PHP?
• PHP runs on various platforms
What You Should Already Know
(Windows, Linux, Unix, Mac OS X, etc.)
Before you continue you should have a
• PHP is compatible with almost all
basic understanding of the following:
servers used today (Apache, IIS, etc.)
• HTML
• PHP supports a wide range of databases
• CSS
• PHP is free. Download it from the official
• JavaScript
PHP resource: www.php.net
• PHP is easy to learn and runs efficiently
PHP on the server side.
• PHP is an acronym for "PHP: Hypertext
Preprocessor"
INTRODUCTION TO PHP
• PHP is a widely-used, open source
scripting language
• PHP scripts are executed on the server PHP is one of the most widely used
• PHP is free to download and use server-side scripting language for web
development. Popular websites like
Facebook, Yahoo, Wikipedia etc., and our
PHP is an amazing and popular
very own Study tonight, are developed
language!
using PHP.
• It is powerful enough to be at the core of
the biggest blogging system on the web
PHP is so popular because it's very simple
(WordPress)!
to learn, code and deploy on server, hence
• It is deep enough to run the largest
it has been the first choice for beginners
social network (Facebook)!
since decades.
• It is also easy enough to be a beginner's
first server-side language!
In this tutorial series we will be covering all
the important concepts of Php language
PHP File from basics to advanced and will also
• PHP files can contain text, HTML, CSS, share some ready-to-use, useful code
JavaScript, and PHP code snippets for beginners to kickstart their
• PHP code is executed on the server, and web development project.
the result is returned to the browser as
plain HTML PHP
• PHP files have extension ".php"
PHP stands for Hypertext Pre-Processor.
PHP is a scripting language used to
PHP Do develop static and dynamic webpages and
• PHP can generate dynamic page content web applications. Here are a few
• PHP can create, open, read, write, important things you must know about
delete, and close files on the server PHP:
6. With PHP, you can create static and
1. PHP is an Interpreted language; dynamic webpages, perform file handling
hence it doesn't need a compiler. operations, send emails, access, and
2. To run and execute PHP code, we modify browser cookies, and almost
need a Web server on which PHP must be everything else that you might want to
installed. implement in your web project.
3. PHP is a server side scripting 7. PHP is fast as compared to other
language, which means that PHP is scripting languages like JSP and ASP.
executed on the server and the result is 8. PHP has in-built support for MySQL,
sent to the browser in plain HTML. which is one of the most widely used
4. PHP is open source and free. Database management system.
Prerequisite for starting with PHP. These are some of the main features of
PHP, while as you will learn the language
- Although we will cover all the concepts you will realize that apart from these
related to PHP in this tutorial series, but features,
you must have a basic understanding of
HTML before starting with this tutorial. Uses of PHP
To further fortify your trust in PHP, here
PHP the right language are a few applications of this amazing
If you are still confused about whether you scripting language:
should learn PHP or is PHP the right 1. It can be used to create Web
language for your web project, then here applications like Social Networks
we have listed down some of the features (Facebook, Digg), Blogs (Wordpress,
and use cases of PHP language, which Joomla), eCommerce websites
will help you understand how simple, yet (OpenCart, Magento etc.) etc.
powerful PHP scripting language is and
why you should learn it. 2. Command Line Scripting. You can
write PHP scripts to perform different
1. PHP is open source and free, hence operations on any machine, all you need
you can freely download, install, and start is a PHP parser for this.
developing using it.
2. PHP has a very simple and easy to 3. Create Facebook applications and
understand syntax, hence the learning easily integrate Facebook plugins in your
curve is smaller as compared to other website, using Facebook's PHP SDK.
scripting languages like JSP, ASP etc.
3. PHP is cross platform; hence you 4. Sending Emails or building email
can easily develop and move/deploy your applications because PHP provides with a
PHP code/project to almost all the major robust email sending function.
operating systems like Windows, Linux,
Mac OSX etc. 5. Wordpress is one of the most used
4. All the popular web hosting services bloggings (CMS) platform in the World,
support PHP. Also, the web hosting plans and if you know PHP, you can try a hand
for PHP are generally the amongst the in Wordpress plugin development.
cheapest plans because of its popularity.
5. Popular Content Management PHP started out as a small open source
Systems like Joomla, Drupal etc. are project that evolved as more and more
developed in PHP and if you want to start people found out how useful it was.
your own website like Study tonight, you Rasmus Lerdorf unleashed the first
can easily do that with PHP. version of PHP way back in 1994.
Characteristics of PHP
• PHP is a recursive acronym for "PHP: Five important characteristics make PHP's
Hypertext Preprocessor". practical nature possible:
• PHP is a server side scripting • Simplicity
language that is embedded in HTML. It is • Efficiency
used to manage dynamic content, • Security
databases, session tracking, even build • Flexibility
entire e-commerce sites. • Familiarity
• It is integrated with a number of
popular databases, including MySQL,
PHP IN THE WEB ENVIRONMENT
PostgreSQL, Oracle, Sybase, Informix,
and Microsoft SQL Server.
• PHP is pleasingly zippy in its PHP programs are written using a text
execution, especially when compiled as an editor, such as Notepad, Simple Text, or
Apache module on the Unix side. The vi, just like HTML pages. However, unlike
MySQL server, once started, executes HTML, PHP files end with a .php
even very complex queries with huge extension. This extension signifies to the
result sets in record-setting time. server that it needs to parse the PHP
• PHP supports a large number of major code before sending the resulting HTML
protocols such as POP3, IMAP, and code to the viewer’s web browser. In PHP,
LDAP. PHP4 added support for Java and on the fly method is adopted to publish the
distributed object architectures (COM document. Hence, the PHP developer
and CORBA), making n-tier development can generate not only web pages, but also
a possibility for the first time. other web embedding documents like
• PHP is forgiving: PHP language tries PDF, PNG, GIF, etc. The PHP web
to be as forgiving as possible. environment is usually set with AMP
• PHP Syntax is C-Like. (Apache, MySQL, and
PHP/Perl/Python), which are linked
together.
Common Uses of PHP
PHP performs system functions, i.e., from
files on a system it can create, open, read, How PHP Fits with HTML
write, and close them. The other uses of PHP not only allows HTML pages to be
PHP are: created on the fly, but it is invisible to your
web site visitors. The only thing they see
• PHP can handle forms, i.e., gather when they view the source of your code is
data from files, save data to a file, thru the resulting HTML output. In this
email you can send data, return data to respect, PHP gives you a bit more security
the user. by hiding your programming logic.
• You add, delete, modify elements HTML can also be written inside the PHP
within your database thru PHP. code of your page, which allows you to
format text while keeping blocks of code
• Access cookies variables and set together. This will also help you write
cookies. organized, efficient code, and the browser
(and, more importantly, the person
• Using PHP, you can restrict users to viewing the site) won’t know the
access some pages of your website. difference.
- is a tool written in PHP intended to − PHP will work with virtually all Web
handle the administration of MySQL over Server software, including Microsoft's
the Web. Currently it can create and drop Internet Information Server (IIS) but then
databases, create/drop/alter tables, most often used is freely available Apache
delete/edit/add fields, execute any SQL Server. Download Apache for free here −
statement, manage keys on fields. https://httpd.apache.org/download.cgi
Step 4:
Now create your own folder under htdocs, o 50,000 users were using PHP to
Example name it as test or whatever. enhance their Web pages
o Developers joined Lerdorf o new language features and constructs
(64 bit type integer, foreach looping)
1999 (PHP 4.0)
PHP KEY CATEGORIES
o with core developers Zeev Suraski and
Andi Gutmans
Practicality
o PHP makes the most popular scripting
language with more than one million user
o PHP is a loosely type language (no
bases by Netcraff
explicitly create, typecast, or destroy a
o Hundreds of functions being added
variable)
o Dubbed the Zend scripting engine
Power
May 22, 2000 (PHP 4.0)
o More libraries and thousands of
o PHP: Hypertext Preprocessor
functions
(recursive acronym)
o 3.6 million domain PHP installed
Possibility
o Enterprise development
▪ Improved resource handling
o Native support is offered for more than
(scalability)
25 database products, including Adabas
▪ Object oriented support (Classes and
D, dBase, Empress, FilePro , FrontBase ,
Objects)
Hyperwave , IBM DB2, Informix, Ingres,
▪ Native session handling support
InterBase , mSQL , Microsoft SQL
(session)
Server, MySQL, Oracle, Ovrimos ,
▪ Encryption (encryption algorithms)
PostgreSQL, Solid, Sybase, Unix dbm ,
▪ ISAPI Support (for IIS)
and Velocis Both structured and Object
▪ Native COM/DOM (Windows
Oriented approach
applications)
▪ Native Java Support: (binding to java
Price
objects)
▪ PERL Compatible Regular
o Free of charge
Expressions
o new features, power, and scalabilty
End Device >> Page Request >> Internet
>> Page Request >> Server >> Scripts /
PHP 5 (July 13, 2004)
Database >> HTML >> Internet >> HTML
>> End Device
o Vastly improved object oriented
capabilities: OOP improvement
o Try/catch exception handling
o Improved XML and Web Services
support (Simple XML Support, using
SOAP)
o Native support for SQLite
o Installed on 19 million domains
o 54 percent on all Apache module
- allow for multiple items of the same type PHP OPERATORS AND CONTROL
to be aggregated under a single STRUCTURES
representative entity.
- (Array and Objects)
Operators
An operator is a symbol that specifies a
PHP Type Casting Operators
particular action in an expression.
Cast Operators Conversion
(array) Array Operator Precedence, Associativity,
(bool) or (Boolean) Boolean and Purpose
(int) or (integer) Integer
(int64) 64-bit integer Operator Associativity Purpose
(introduced in PHP new NA Object instantiation
() NA Expression
6) subgrouping
(object) Object [] Right Index enclosure
(real) or (double) Float ! ~ ++ -- Right Boolean NOT,
or (float) bitwise NOT,
(string) String increment,
decrement
@ Right Error suppression
PREDEFINED TYPE FUNCTIONS /*% Left Division,
multiplication,
modulus
gettype() function +-. Left Addition,
subtraction,
concatenation
- returns the type of the variable. Possible << >> Left Shift left, shift right
return values are integer, double, boolean, (bitwise)
< <= > >= NA Less than, less
string, array, object, resource, unknown than or equal to,
types. greater than,
greater than or
equal to
prototype:
&^| Left Bitwise AND,
bitwise XOR,
string gettype(mixed var) bitwise OR
&& || Left Boolean AND
Boolean OR
settype() function ?: Right Ternary operator
= += *= /= Right Assignment
- converts a given variable to a specific .= %= &= operators
type. AND Left Boolean AND,
XOR OR Boolean XOR,
prototype: Boolean OR
boolean settype(mixed var, string type) , Left Expression
is_array(), is_bool(), is_float(), separation;
example: $days =
is_integer(), is_null(), is_numeric(), array (1=>
is_object(), is_resource(), is_scalar(), “Monday”, 2=>”
and is_string() Tuesday”)
Operator Precedence
is a characteristic of operators that
determines the order in which they
evaluate the operands surrounding them.
<?php $x = $y = $x = $c;
$price = 450; echo "<p>$x</p>";
$discount = 12; //is also same as
$value = $price - $price * ($x = ($y = ($z = $c))); //right
$discount / 100; to lefts
echo "<p>$value pesos</p>"; echo "<p>$x</p>";
//is the same as ?>
$value = ($price -
(($price*$discount)/100));
echo "<p>$value pesos</p>";
?>
Output:
Output:
Arithmetic Operator
Operator Associativity
Example Label Outcome
is a characteristic of an operator specifies
$a + $b Addition Sum of $a
how operations of the same precedence
and $b
are evaluated as they are executed.
$a - $b Subtraction Difference of
$a and $b
Example: $a * $b Multiplication Product of $a
and $b
<?php $a / $b Division Quotient of $a
$a = 600; and $b
$b = 30; $a % $b Modulus Remainder of
$c = 5; $a divided by
$x = $a / $b * $c; $b
echo "<p>$x</p>";
//is also same as Assignment Operator
$x = (($a / $b)* $c); //left to
right Example Label Outcome
echo "<p>$x</p>"; $a = 5 Assignment $a equals 5
$a += 5 Addition- $a equal $a Output:
assignment plus 5
$a *= 5 Multiplication- $a equal $a
assignment multiplied by 5
$a /= 5 Division- $a equal $a
assignment divided by 5
$a .= 5 Concatenation- $a equal $a
assignment concatenated
with 5
<?php
$a = 135; $b = 45;
$c = $a & $b;
echo "<p>$c</p>";
Logical Operator $c = $a | $b;
echo "<p>$c</p>";
Example Label Outcome $c = $a ^ $b;
$a && $b AND True if both $a and echo "<p>$c</p>";
$b are true
$c = ~$b;
$a AND $b AND True if both $a and
$b are true echo "<p>$c</p>";
$a || $b OR True if either $a or $b $c = $b << 2;
is true
$a OR $b OR True if either $a or $b
echo "<p>$c</p>";
is true $c = $a >> 2;
!$a NOT True if $a is not true echo "<p>$c</p>";
NOT $a NOT True if $a is not true
$a XOR $b Exclusive True if only $a or only
?>
OR $b is true
Equality Operator
Bitwise Operator
if(expression) {
statement…
} else {
statement
}
elseif statement
syntax:
if(expression) {
statement…
} elseif (expression) { Output:
statement…
} else {
statement…
}
Example:
<?php
$a = 50; $b = 80; Nested if…else
//if statement
if($a < $b){ Example:
echo "<p>\$a is less than
\$b</p>"; <?php
} $score = 86;
//if...else statement if($score > 80){
if($score < 91){
echo "Your score is
between 80 to 91";
} else{
echo "Your score is
higher than 90";
}
} else{
echo "Your score is lower
Output:
than 81";
}
?>
switch statement
syntax:
switch($category){
case opt1:
statement…
break;
case opt2:
Output: statement…
break;
case opt3:
statement…
break; …
Compound expression using logical default:
operators. statement…
}
Example:
Switch Statement
<?php
$score = 86; Example:
if($score > 80 && $score < 91){
echo "Your score is between <?php
80 to 91"; $month = 2;
} else if($score > 90){ switch($month){
echo "Your score is higher case 1:
than 90"; echo "January"; break;
} else { case 2:
echo "Your score is lower echo "February"; break;
than 81"; case 3:
} echo "March"; break;
?> case 4:
echo "and so on up to
12"; break;
default:
echo "Invalid"; break;
}
?>
}
echo "<br/>";
$y = 20;
do{
echo $y++." ";
} while($y<21);
echo "<br/>";
$z=5;
for($i=$z;$i>0;$i--){
echo $i." ";
}
Output: ?>
Looping Statements
while statement
syntax:
while(expression) {
statement…
}
do…while statement
syntax: Output:
do {
statement…
} while(expression);
for statement
break, continue, and goto statement.
syntax:
break
for (expr1; expr2; expr3) {
- break statement is placed within the
statement…
code of a loop to cause the program to
}
break out of the loop statement.
Example:
continue
Example:
<?php
$i=1;
while(true){ alternative enclosure syntax
$i++; Involves replacing the opening bracket
with a colon(:) and replacing the closing
if($i<20){
bracket with endif;, endwhile;,endfor;,
continue;
endswitch
} elseif($i>=20 && $i<30){
echo $i."<br/>";
Example:
} else{
break;
<?php
}
$a = 10; $b = 20; $c = 30;
}
if($a<$b):
goto display;
echo "<p>\$a is less than
echo "This statement were
\$b</p>";
skipped by goto";
endif;
display:
for($i=1;$i<11;$i++):
echo "statement from display
echo $i." ";
label";
endfor;
?>
?>
Output:
Output:
Summary
Operator in PHP
Operators are symbols that tell the PHP
processor to perform certain actions. For
example, the addition (+) symbol is an
operator that tells PHP to add two
PHP Assignment Operators
variables or values, while the greater-
The assignment operators are used to
than (>) symbol is an operator that tells
assign values to variables.
PHP to compare two values.
$x = 100; <?php
$x %= 15; $x = 25;
echo $x; // Outputs: 10 $y = 35;
?> $z = "25";
var_dump($x == $z); // Outputs: boolean
true
var_dump($x === $z); // Outputs: boolean
false
var_dump($x != $y); // Outputs: boolean Run this code >>
true
var_dump($x !== $z); // Outputs: boolean <?php
true $x = 10;
var_dump($x < $y); // Outputs: boolean echo ++$x; // Outputs: 11
true echo $x; // Outputs: 11
var_dump($x > $y); // Outputs: boolean
false $x = 10;
var_dump($x <= $y); // Outputs: boolean echo $x++; // Outputs: 10
true echo $x; // Outputs: 11
var_dump($x >= $y); // Outputs: boolean
false $x = 10;
?> echo --$x; // Outputs: 9
echo $x; // Outputs: 9
Output:
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
Output:
Example:
Run this code >>
PHP Array Operators
<?php The array operators are used to compare
$year = 2014; arrays:
// Leap years are divisible by 400 or by 4
but not 100 Operator Name Example Result
if(($year % 400 == 0) || (($year % 100 != + Union $x + $y Union of $x and
$y
0) && ($year % 4 == == Equality $x == $y True if $x and $y
0))){ have the same
echo "$year is a leap year."; key/value pairs
} else{ === Identity $x === True if $x and $y
$y have the same
echo "$year is not a leap year."; key/value pars in
} the same order
?> and of the same
types
!= Inequality $x != $y True if $x is not
Output: equal to $y
<> Inequality $x <> $y True if $x is not
equal to $y
!== Non- $x !== $y True if $x is not
identity identical to $y
Output:
// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo "x" <=> "y"; // Outputs: -1
echo "y" <=> "x"; // Outputs: 1
?>
PHP supports a number of different
control structures:
• if
• else
• elseif
• switch
• while
• do - while
• for
• foreach
• and more
Let's take a look at a few of these control
structures with examples.
As you can see in the above diagram, first
a condition is checked. If the condition is Go Through the Different Control
true, the conditional code will be executed. Structures
The important thing to note here is that In the previous section, we learned the
code execution continues normally after basics of control structures in PHP and
conditional code execution. their usefulness in application
development. In this section, we'll go
Let's consider the following example. through a couple of important control
structures that you'll end up using
Start >> Check if user is logged in or not frequently in your day-to-day application
>> User is logged in >> Redirect User to development.
My Account Page
If
Start >> Check if user is logged in or not
>> User is not logged in >> Redirect User - The if construct allows you to execute a
to Login Page piece of code if the expression provided
along with it evaluates to true.
<?php
$age = 50;
if ($age > 30)
{
echo "Your age is greater than 30!";
}
In the above example, the program checks ?>
whether or not the user is logged in.
Based on the user's login status, they will Output:
be redirected to either the Login page or
the My Account page. In this case, a
control structure ends code execution by
redirecting users to a different page. This
is a crucial ability of the PHP language.
- The above example should output the
Your age is greater than 30! message
since the expression evaluates to true. In
fact, if you want to execute only a single
statement, the above example can be
rewritten as shown in the following snippet
without brackets.
<?php
Else
$age = 50;
- In the previous section, we discussed the
if ($age > 30)
if construct, which allows you to execute a
echo "Your age is greater than 30!";
piece of code if the expression evaluates
?>
to true. On the other hand, if the
expression evaluates to false, it won't do
Output:
anything. More often than not, you also
want to execute a different code snippet if
the expression evaluates to false. That's
where the else statement comes into the
picture.
if (expression)
- On the other hand, if you have more than {
one statements to execute, you must use // code is executed if the expression
brackets, as shown in the following evaluates to TRUE
snippet. }
else
<?php {
if (is_array($user)) // code is executed if the expression
{ evaluates to FALSE
$user_id = isset($user['user_id']) ? }
$user['user_id'] : '';
$username = isset($user['username']) ? - Let's revise the previous example to
$user['username'] : ''; understand how it works.
// and more statements...
} <?php
?> $age = 50;
if (expression1)
{
// code is executed if the expression1 - As you can see in the above example,
evaluates to TRUE we have multiple conditions, so we've
} used a series of elseif statements. In the
elseif (expression2) event that all if conditions evaluate to
{ false, it executes the code provided in the
// code is executed if the expression2 last else statement.
evaluates to TRUE
} Switch
elseif (expression3)
{ - The switch statement is somewhat
// code is executed if the expression3 similar to the elseif statement which we've
evaluates to TRUE just discussed in the previous section. The
} only difference is the expression which is
else being checked.
{
// code is executed if the expression1, - In the case of the elseif statement, you
expression2 and expression3 evaluates to have a set of different conditions, and an
FALSE, a default appropriate action will be executed based
choice on a condition. On the other hand, if you
}
want to compare a variable with different matched with a case, the code associated
values, you can use the switch statement. with that case block will be executed. After
that, you need to use the break statement
- As usual, an example is the best way to to end code execution. If you don't use the
understand the switch statement. break statement, script execution will be
continued up to the last block in the switch
<?php statement.
$favourite_site = 'Code';
- Finally, if you want to execute a piece of
switch ($favourite_site) { code if the variable's value doesn't match
case 'Business': any case, you can define it under the
echo "My favourite site is default block. Of course, it's not
business.tutsplus.com!"; mandatory—it's just a way to provide a
break; default case.
case 'Code':
echo "My favourite site is - So that's the story of conditional control
code.tutsplus.com!"; structures. We'll discuss loops in PHP in
break; the next section.
case 'Web Design':
echo "My favourite site is LOOPS
webdesign.tutsplus.com!";
break;
- Loops in PHP are useful when you want
case 'Music':
to execute a piece of code repeatedly until
echo "My favourite site is
a condition evaluates to false. So, code is
music.tutsplus.com!";
executed repeatedly as long as a
break;
condition evaluates to true, and as soon
case 'Photography':
as the condition evaluates to false, the
echo "My favourite site is
script continues executing the code after
photography.tutsplus.com!";
the loop.
break;
default:
- The following flowchart explains how
echo "I like everything at tutsplus.com!";
loops work in PHP.
}
?>
Start >> Condition >> Condition is TRUE
>> Conditional Code is executed >>
Output:
Condition >> Condition is False >> Code
after loop continues.
Output:
As you can see in the above screenshot, a
loop contains a condition. If the condition
evaluates to true, the conditional code is
executed. After execution of the
conditional code, control goes back to the - If you're familiar with the Fibonacci
loop condition, and the flow continues until series, you might recognize what the
the condition evaluates to false. above program does—it outputs the
Fibonacci series for the first ten numbers.
In this section, we'll go through the
The while loop is generally used when
different types of loops supported in PHP. you don't know the number of iterations
that are going to take place in a loop.
While Loop
Do-While Loop
- The while loop is used when you want to
execute a piece of code repeatedly until - The do-while loop is very similar to the
the while condition evaluates to false.
while loop, with the only difference being
that the while condition is checked at the
- You can define it as shown in the end of the first iteration. Thus, we can
following pseudo code. guarantee that the loop code is executed
at least once, irrespective of the result of
while (expression)
the while expression.
{
// code to execute as long as expression - Let's have a look at the syntax of the do-
evaluates to TRUE while loop.
}
do
- Let's have a look at a real-world example {
to understand how the while loop works in // code to execute
PHP. } while (expression);
<?php Let's go through a real-world to
$max = 0; understand possible use-cases where you
echo $i = 0; can use the do-while loop.
echo ",";
echo $j = 1; <?php
echo ","; $handle = fopen("file.txt", "r");
$result=0; if ($handle)
{ - Let's go through the following example to
do see how it works.
{
$line = fgets($handle); <?php
for ($i=1; $i<=10; ++$i)
// process the line content {
echo sprintf("The square of %d is
} while($line !== false); %d.</br>", $i, $i*$i);
} }
fclose($handle); ?>
?>
Output:
In the above example, we're trying to read
a file line by line. Firstly, we've opened a
file for reading. In our case, we're not sure
if the file contains any content at all. Thus,
we need to execute the fgets function at
least once to check if a file contains any
content. So, we can use the do-while loop
here. do-while evaluates the condition
after the first iteration of the loop.
For Loop
If Statements
Outline
• { } Statement
• if…else
• if…elseif
• switch
• break
• while
• do…while
• for
Example
Making Decisions <?php
• Decision making or flow control is the if(isset($_GET["myNumber"])) {
process of determining the order in which $a = $_GET["myNumber"];
statements execute in a program echo “ตวัเลขทีก่ รอก คือ ".$a;
if(a>10)
่
echo “ตวเััลขทีก่ รอกมคีามากกวาั่ ั่ 10”;
}
?>
Output:
if…else Statements
<?php
$a =19;
if($a == 1)
echo “one”;
elseif($a == 2)
echo “two”;
elseif($a == 3)
echo “three”;
elseif($a == 4)
echo “four”;
else
• An if statement can be constructed echo “more than four”;
without the else clause ?>
• The else clause can only be used with an
if statement Output:
Example:
<?php
$a =1; Switch Statements
$b = 2;
if($a > $b) • The same variable is compared with
echo “a is greater than b”; many different values
else • The default statement is used if none of
echo “a is less than or equal to b”; the cases are true
?> • Statements are executed until it sees a
break statement
• The syntax for a switch statement is:
<body>
switch ($variable_name) { <form action= "switch1.php" method=
case valueA: "GET">
statements; Select a language:
break; // optional <select name = "myLanguage" >
case valueB: <option value= "TH"> Thailand </option>
statements; <option value= "EN"> English </option>
break; // optional <option value= "CH"> Chinese </option>
default: <option value= "JP"> Japanese </option>
statements; </select>
} <input type = "submit" value = "NO">
<hr>
break </form>
Output:
NO
Select a language:
while
Example:
• It tells PHP to execute the nested
<!DOCTYPE html>
statements repeatedly, as long as the
<html>
while expression evaluates to TRUE
<head>
<meta charset="utf-8"> </meta>
</head>
• If the first evaluation of the statement • The truth expression is checked at the
return FALSE, the while loop will not be end of each iteration instead of in the
executed at all beginning.
• The syntax for while statement is: • The syntax for an do...while statement is:
while >> Condition >> True >> Statement do…while >> Statement >> True >>
>> Condition >> False Condition >> Statement >> Condition >>
False
while >> Condition >> False
do…while >> Statement >> Condition >>
False
Example:
<?php
$x=1;
while($x <= 5) { <?php
echo "The number is: $x <br>"; $x=1;
$x++; do {
} echo "The number is: $x <br>";
?> $x++;
} while ($x <= 5 );
Output: ?>
Output:
do…while.
Output:
Example:
for <?php
for($i = 1; $i < 10; $i++) {
• for loop is used if you know how many echo "The number is $i ";
times you want to execute the statements }
• The syntax for for statement is: ?>
for(initial;condition;inc/dec){ Output:
statement;
statement;
}
for >> Condition >> True >> Statement >> An operator is a symbol that specifies a
Condition >> False particular action in an expression.
Conditional Statements
Equality Operator
if statement
Example Label Outcome
$a == $b Is equal to True if $a syntax:
and $b are
equivalent if(expression) {
$a != $b Is not equal True if $a is statement…
to not equal to
}
$b
$a === $b Is identical True if $a
to and $b are else statement
equivalent
and $a and syntax:
$b have the
same type if(expression) {
statement…
Bitwise Operator } else {
statement
Example Label Outcome }
$a & $b AND And together each bit
contained in $a and $b elseif statement
$a | $b OR Or together each bit
contained in $a and $b
$a ^ $b XOR Exclusive-or together syntax:
each bit contained in $a
and $b if(expression) {
~ $b NOT Negate each bit in $b
$a << $b Shift $a will receive the
statement…
left value of $b shifted left } elseif (expression) {
two bits statement…
$a >> $b Shift $a will receive the } else {
right value of $b shifted right
two bits statement…
}
Escape Sequences
Nested if…else
Sequence Description
\n Newline character Example:
\r Carriage return
\t Horizontal tab <?php
\\ Backlash $score = 86;
\$ Dollar sign if($score > 80){
\” Double quote if($score < 91){
\[0-7] {1,3} Octal notation echo "Your score is
\x[0-9A-Fa-f]{1,2} Hexadecimal
between 80 to 91";
notation
} else{
echo "Your score is
higher than 90";
}
} else{
echo "Your score is lower Conditional Statements
than 81";
} switch statement
?>
syntax:
switch($category){
case opt1:
statement…
break;
case opt2:
statement…
break;
case opt3:
Output:
statement…
break; …
default:
statement…
Conditional Statements Compound }
expression using logical operators.
Conditional Statements Switch
Example: Statement
<?php Example:
$score = 86;
if($score > 80 && $score < 91){ <?php
echo "Your score is between $month = 2;
80 to 91"; switch($month){
} else if($score > 90){ case 1:
echo "Your score is higher echo "January"; break;
than 90"; case 2:
} else { echo "February"; break;
echo "Your score is lower case 3:
than 81"; echo "March"; break;
} case 4:
?> echo "and so on up to
12"; break;
default:
echo "Invalid"; break;
}
?>
Output:
} while(expression);
for statement
syntax:
do {
statement…
APPLICATIONS DEVELOPMENT AND EMERGING TECHNOLOGIES
QUESTIONNAIRE
FORMATIVE 1 7.) All php files must be save on htdocs
folder.
1.) Try/catch exception handling introduce
in what version of PHP. A. True
B. False
A. PHP3
B. PHP2 8.) In what year PHP 5 released
C. PHP4
D.PHP5 A. 2002
B. 2001
2.) IN PHP 5 how many percent on all C. 2004
Apache module D. 2003
A. Dreamweaver A. True
B. Notepad++ B. False – are case sensitive
C. Netbeans
D. Mspaint 12.) returns the type of the variable.
Possible return values are integer, double,
6.) What is the url is use to open your boolean, string, array, object, resource,
created php files unknown types.
A. yahoo A. gettype()
B. localhost B. typeset()
C. google C. settype()
D. mydrive D. typeget()
13.) Setting the identifier for a variable C. Vista
must follow some rules. D. XP
A. PHP 5 A. #
B. PHP 4 B. $
C. PHP 3 C. @
D. PHP 6 D. ^
19.) Asp style tag 26.) allow for multiple items of the same
type to be aggregated under a single
A. <?...?> representative entity. (Array and Objects)
B. </…/>
C. <(…)> A. Compound datatypes
D. <%...%> B. Modular datatypes
C. Scalar datatypes
20.) Which of the following is not Windows D. Single datatypes
OS?
A. Cheetah
B. 2000
27.) To display the string that starts with $
and to display the double quote as string 35.) Script tag
use the escape character \ (backlash).
A. </script>
A. True B. </scr>
B. False C. </sct>
D. <scrpt>
28.) PHP can use in Linux.
36.) What is the default location of
A. False XAMPP?
B. True
A. E:\
29.) Which of the following is not Mac OS B. D:\
C. C:\
A. Giraffe D. F:\
B. Cheetah
C. Jaguar 37.) In what year PHP 2.0 released
D. Puma
A. 2000
30.) Software used to run PHP Scripts B. 1997
C. 1999
A. Mspaint D. 1998
B. Netbeans
C. Notepad++ 38.) PHP created 1994/1995 t know how
D. XAMPP many visitors were reading his online
resume based on
31.) What is OS?
A. CSS page
A. Operation System B. JavaScript page
B. Outgoing System C. PERL/CGI script
C. Operating System D. HTML page
D. Out System
39.) Term used to combine two or more
32.) HTML is one the requirements to use different strings.
PHP.
A. Concatenate
A. True B. Plus
B. False C. Combine
D. Concreate
33.) Strings inside the ‘ and’ are
interpreted as literal strings. 40.) PHP can create in code editors.
A. False A. False
B. True B. True
34.) PHP 5 vastly improved 41.) How many domains installed in PHP
5
A. Coding
B. Scripting A. 12 million
C. Designing B. 15 million
D. Object Oriented capabilities C. 19 million
D. 10 million D. Welcome to php
42.) PHP require to use a web browser. 49.) Presented ads character
corresponding to that ASCII value
A. False
B. True A. %c
B. %ch
43.) Open tag for PHP scripts C. %as
D. %a
A. <=
B. <? 50.) $age is a valid variable.
C. ?>
D. => A. False
B. True
44.) $val = “abc”.”def” valid or invalid?
FORMATIVE 2
A. Valid
B. Invalid 1.) PHP can use a database.
A. letters A. False
B. alpha-numeric B. True
C. numeric
D. special characters 4.) $ inside “ and” are interpreted as
variables thus it will display the value
47.) Variables in PHP must begin with rather than the string that starts with $.
A. @ A. True
B. ! B. False
C. $
D. # 5.) recursive acronym for PHP
A. Welcome to PHP
B. ‘welcome to php’
C. “welcome to php”
6.) Setting the identifier for a variable must 13.) Variables in PHP must begin with
follow some rules.
A. $
A. True B. !
B. False C. #
D. @
7.) How many domains installed in PHP 5
14.) Asp style tag
A. 10 million
B. 19 million A. <?...?>
C. 15 million B. </…/>
D. 12 million C. <(…)>
D. <%...%>
8.) Extension name for php files
15.) To display the string that starts with $
A. .p and to display the double quote as string
B. .php use the escape character \ (backlash).
C. .hp
D. .ph A. False
B. True
9.) You can use a sever side scripting
language in PHP. 16.) symbol that specifies a particular
action in an expression.
A. False – server side
B. True A. Associativity
B. Operator
10.) What is OS? C. Purpose
D. Precedence
A. Operation System
B. Outgoing System 17.) Associativity for assignment operators
C. Operating System
D. Out System A. NA
B. Middle
11.) How many types of comment php C. Right
have? D. Left
A. 2 18.) $s=90;
B. 3 if($s==80 && $s<90){
C. 4 echo “Rank B”;
D. 5 } else if($s>90){
echo “Rank A”;
12.) PHP created 1994/1995 t know how }else{
many visitors were reading his online echo “Rank C”;
resume based on }
What is the output if $s=85?
A. PERL/CGI script
B. CSS page A. Rank B
C. JavaScript page B. Rank A
D. HTML page C. Error
D. Rank C
19.) Ternary format }
What is the output if $s= 70?
A. (10 == $a):?1
B. (5 == f):: A. Rank C
C. ($a == 10)?5 B. Error
D. ($a == 12) ? 5 : 1 C. Rank A
D. Rank B
20.) Decrement symbol
27.) Associativity for ternary operator
A. –
B. + A. Right
C. -- B. Left
D. ++ C. Middle
D. NA
21.) You can use many if condition in one
php script 28.) Symbol for less than
A. False A. >
B. True B. >=
C. <
22.) If($a == $b){} D. <=
A. @ A. PHP 2.0
B. {} B. PHP 4.0
C. new C. PHP 3.0
D. start D. PHP 1.0
26.) $s=90; 32.) Symbol use for Perl style single line
if($s==80 && $s<90) { comment
echo “Rank B”;
}else{ A. @
echo “Rank C”; B. #
C. $
D> ^ 40.) In PHP 5 how many percent on all
Apache module
33.) PHP can use in Linux.
A. 54
A. False B. 45
B. True C. 64
D. 34
34.) Presented as a signed decimal
number. 41.) All php files must be save on htdocs
folder.
A. %n
B. %dn A. True
C. %d B. False
D. %nd
42.) How many domains PHP installed on
35.) PHP contains More libraries and May 22, 2000
thousands of functions.
A. 1.6 million
A. False B. 2.6 million
B. True C. 3.6 million
D. 4.6 million
36.) One of the Core developers of php
4.0 43.) Symbol to use value in string.
A. Andi Gutmans A. ++
B. Andi Guman B. “
C. Andi Gusman C. –
D. Andi Gunman D. **
37.) What is the default location of 44.) is the generic name assigned to any
XAMPP? data sharing a common set of
characteristics.
A. C:\
B. F:\ A. Variables
C. D:\ B. Array
D. E:\ C. Output
D. Datatypes
38.) In what year PHP 1.0 released
45.) PHP 5 vastly improved
A. 1995/1996
B. 1997/1998 A. Designing
C. 1996/1997 B. Scripting
D. 1994/1995 C. Object Oriented capabilities
D. Coding
39.) Software used to run PHP Scripts
46.) Associativity for Object instantiation
A. Netbeans
B. Notepad++ A. Right
C. XAMPP B. Middle
D. Mspaint C. NA
D. Left B. 2
C. 3
47.) Symbol for OR operator D. 1
52.) if(expression){
statement
} else {
statement
}
How many condition/s
A. 4
APPLICATIONS DEVELOPMENT AND EMERGING
TECHNOLOGIES REVIEWER
MODULE 3
PHP Arrays and User Defined
Functions
PHP Arrays
Array
ARRAY
Output:
$fruit = array("orange",
"apple",
Functions for visualizing arrays "grapes",
"banana");
print_r() function - short for print echo "<pre>";
recursive. This takes an argument of any var_dump($fruit);
type and prints it out, which includes echo "</pre>";
printing all its parts recursively.
<?php
$fruit = array("orange",
"apple",
"grapes",
"banana"); Looping through array elements
echo "<pre>";
print_r($fruit); foreach() function - is a statement used
echo "</pre>"; to iterate or loop through the element in an
?> array. With each loop, a foreach
statement moves to the next element in an
array.
Multidimensional arrays
Example:
<?php
$person = array(
'Leader' => array(
'First Name' => 'Juan',
'Last Name' => 'Dela
Cruz', Output:
'Date of Birth' =>
'April 3, 1986',
'Gender' => 'Male'),
'Assistant' => array(
'First Name' => 'Rica',
'Last Name' => 'San
Pedro',
'Date of Birth' =>
'January 8, 1980',
'Gender' => 'Female'),
'Member' => array(
'First Name' => 'Jose',
'Last Name' => 'Dela
Paz',
'Date of Birth' =>
'March 2, 1985',
'Gender' => 'Male') Sorting
);
Function Description
foreach($person as $pkey => sort($array) Sort by value;
$parr){
assign new
numbers as the
echo "<h2>$pkey</h2>";
keys
foreach($parr as $key => rsort($array) Sorts by value in
$value){ reverse order;
echo "$key: assign new
$value<br/>";
number as the Output:
keys
asort($array) Sorts by value;
keeps the same
key
arsort($array) Sorts by value in
reverse order;
keeps the same
key
ksort($array) Sorts by key
krsort($array) Sorts by key in
reverse order
usort($array, Sorts by a function
functionname)
Example:
<?php Example:
$fruit = array(
"orange", "apple", <?php
"grapes", "banana", $fruit = array(
"guava", "blue berry"); "orange", "apple",
"grapes", "banana",
sort($fruit); //sort array in "guava", "blue berry");
ascending
echo "<pre>"; asort($fruit);
print_r($fruit); echo "<pre>";
echo "</pre>"; print_r($fruit);
echo "</pre>";
rsort($fruit); //sort array in
descending arsort($fruit);
echo "<pre>"; echo "<pre>";
print_r($fruit); print_r($fruit);
echo "</pre>"; echo "</pre>";
?> ?>
Output:
Output:
Example:
<?php
$fruit = array(
'1010' => "orange",
'1002' => "apple",
'1023' => "grapes",
'1006' => "banana",
'1015' => "guava",
'1009' => "blue berry");
ksort($fruit);
echo "<pre>";
print_r($fruit);
echo "</pre>"; PHP USER DEFINED FUNCTIONS
krsort($fruit); Functions
echo "<pre>";
print_r($fruit); - is a group of PHP statements that
echo "</pre>"; performs a specific task. Functions are
?> designed to allow you to reuse the same
code in different locations.
Predefined functions
function name(param){
//code to be executed by the
function
}
Where
function
- is the keyword used to declare a function
name
- is the name of the function or function Output:
identifier
param
- is the formal parameters of the function.
Parameter must follow the rule of naming
identifier.
Output:
Output:
Nested function
Example:
Example: <?php
function displayPerson(){
function qoutient($x, $y){ function name(){
return $x/$y; echo "Juan Dela Cruz";
} }
}
function remark($grade){
if($grade >= 75){ name();
return true; ?>
} else{
return false;
}
}
printf("The qoutient is
%.2f<br/>", qoutient(7,3));
if(remark(80)){
echo "passed";
} else { Output:
echo "failed";
}
Example:
<?php
function displayPerson(){
function name(){
echo "Juan Dela Cruz";
}
}
displayPerson();
name();
?>
Output:
Example:
<?php
Output: $str = "This is global
variable";
function f(){
global $str;
Variable scope echo "function f () was
called<br>";
Global Variables - is one that declared echo "$str<br>";
outside a function and is available to all }
parts of the program. f();
?>
Local Variables - is declared inside a
function and is only available within the
function in which it is declared.
using variables
Example:
Output:
<?php
$str = "This is global
variable";
function f(){ Example:
echo "function f () was
called<br>"; <?php
echo "$str<br>"; function f(){
} $str = "This is local
f(); variable";
?> }
f();
echo "Displaying local variable:
" ;
echo $str;
?>
counter(4);
counter(3);
counter(8);
counter(6);
?>
Output:
Example:
<?php
function f(){ Output:
global $str;
$str = "This is local
variable";
}
f();
echo "Displaying local variable:
" ; Summary
echo $str; • Array is used to aggregate a series of
?> similar items together.
• Array index references a corresponding
value.
• Array index can be simple numerical or
have some direct correlation to the value.
• Array index is also known as Array Keys.
• print_r function is used to print the array
structure.
• var_dump function is same as print_r
function except it adds additional
Output: information about the data of each
element.
• The foreach statement is use to iterate
through the element in an array.
• Using foreach statement you can display
Example: both the keys and value of each element
in the array.
<?php • PHP provides functions for array
function counter($value){ manipulation such as sort (), rsort(),
static $count = 0; asort(), arsort(), ksort(), krsort(), and
$count += $value; usort() functions.
echo "The value of the • sort(), asort(), and ksort() functions
counter is $count<br>"; are used to sort elements in the array in
} ascending order.
• rsort(), arsort(), and krsort() functions Numeric array
are used to sort elements in the array in
descending order. - An array with a numeric index. Values
• sort() and rsort() does not maintain its are stored and accessed in linear fashion.
index reference for each values.
• asort(), ksort(), arsort(), and krsort() Associative array
maintains its reference for each values.
• asort() and arsort() used to sort - An array with strings as index. This store
elements by values. element values in association with key
• ksort() and krsort() used to sort values rather than in a strict linear index
elements by keys. order.
• Functions is a group of PHP statements
that performs a specific task. Multidimensional array
• Functions can be user defined generally
defined by the user of the program and - An array containing one or more arrays
predefined that are build in using libraries. and values are accessed using multiple
• You use functions in different ways. indices
Function can only do something without
passing values. You can pass values to a NOTE - Built-in array functions is given in
function, and you can ask functions to function reference PHP Array Functions
return a value.
• function keyword is used in PHP to Numeric Array
declare a function. Following is the example showing how to
• A function that is declared inside a create and access numeric arrays.
function is said to be hidden. Here we have used array() function to
• To gain access to a variable that is create array. This function is explained in
outside from the function we use the function reference.
global keyword.
• We use static keyword to declare a <html>
variable inside a function that will act as <body>
accumulator variable this will let the
program remember the last value of the <?php
variable that was used. /* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
SUPPLEMENTARY
foreach( $numbers as $value ) {
ARRAY echo "Value is $value <br />";
}
An array is a data structure that stores one
or more similar type of values in a single /* Second method to create array. */
value. For example, if you want to store $numbers[0] = "one";
100 numbers then instead of defining 100 $numbers[1] = "two";
variables its easy to define an array of $numbers[2] = "three";
100 length. $numbers[3] = "four";
$numbers[4] = "five";
There are three different kinds of arrays,
and each array value is accessed using an foreach( $numbers as $value ) {
ID c which is called array index. echo "Value is $value <br />";
}
?>
echo "Salary of mohammad is ".
</body> $salaries['mohammad'] .
</html> "<br />";
echo "Salary of qadir is ".
This will produce the following result – $salaries['qadir']. "<br />";
echo "Salary of zara is ".
Output: $salaries['zara']. "<br />";
</body>
</html>
Output: <?php
$vec_1 =
Marks for mohammad in physics : 35 array("moshe","david","john");
echo "simple array of strings"; Output:
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>
Output:
<?php
<?php $vec = array(2,4,5,123,2221,”sda”);
$vec_1 = var_dump($vec);
array(100=>"moshe",101=>"david",102 ?>
=>"john");
echo "simple array of strings and their Output:
keys";
echo "<BR>".$vec_1[100];
echo "<BR>".$vec_1[101];
echo "<BR>".$vec_1[102]; • Using var_dump() function we can print
?> out more than one array.
Output: <?php
$vec_1 = array(2,4,5,123,2221);
$vec_2 = array(24,442,32,84,110);
$vec_3 = array(10,20,30,40,50);
var_dump($vec_1,$vec_2,$vec_3);
?>
Output:
<?php
$vec_1 =
array("m"=>"moshe","d"=>"david","j"=
>"john");
echo "simple array of strings and their
keys";
echo "<BR>".$vec_1["m"];
echo "<BR>".$vec_1["d"];
echo "<BR>".$vec_1["j"];
?>
<?php
$matrix = array();
$matrix[0] = array("a","b");
$matrix[1] = array("c","d");
echo $matrix[0][0];
echo $matrix[0][1];
echo $matrix[1][0];
echo $matrix[1][1];
?>
Output:
Output:
Array Inner Structure
• PHP arrays behave like ordered map.
As such, they allow various
possibilities:
PHP arrays can be used to simulate
different types of structures (e.g., map, <?php
queue, stack etc...). $vec =
PHP arrays can have unique keys, both [2=>"dave",1=>"ron",0=>"chen",3=>"ra
numeric and textual. When using numeric n"];
ones, they don't need to be sequential. list($a,$b,$c) = $vec;
echo "<br>a=$a";
Multi Dimensional Arrays echo "<br>b=$b";
• A multidimensional array is an array that echo "<br>c=$c";
each one of its elements is another array. ?>
<?php
Output: $vec_1 = array(1,2,3);
$vec_2 = array(3,4,5,6);
$vec_3 = $vec_1 + $vec_2;
var_dump($vec_3);
?>
<?php
$matrix = [
["haim", "michael", 344537565],
["mosh", "solomon", 452234343],
The ‘==’ and ‘===’ Operators
["ron","kalmon",453234234]
The '==' operator (equality) returns true
];
if the following condition fulfills:
foreach ($matrix as list($fname,
1. The two arrays contain the same
$lname,$id))
elements.
{
The '===' operator (non identity)
echo "fname:$fname lname:$lname
returns true if each one of the following
id:$id ";
two conditions fulfills:
}
1. The two arrays contain the same
?>
elements.
2. The two arrays have their identical
Output:
elements in the same position.
<?php
//$a =
['a'=>'avodado','b'=>'bamba','c'=>'calco'
];
//$b =
['b'=>'bamba','a'=>'avodado','c'=>'calco'
];
$a = [123,455,323];
$b = [323,123,455];
if($a==$b)
{
echo "a and b equal";
}
else
{
echo "a and b not equal";
}
The ‘+’ Operator ?>
• Using the + operator on two arrays we
will get a union of the two arrays. Result: a and b not equal
• Union of two arrays will include a union
of the keys each one of the two arrays
have and the values assigned with each
one of them.
The ‘!=’ and ‘!==’ Operators var_dump($vec_2!=$vec_5); //false
The '!=' operator (inequality) returns var_dump($vec_2!==$vec_5); //true
true if the following condition doesn't ?>
fulfill:
1. The two arrays contain the same Output:
elements.
The '!==' operator (non identity) returns
true if at least one of the following two
conditions doesn't fulfill:
Example <?php
$vec = array(1,2,3,4,5,6,7,8);
<?php echo count($vec);
$vec_1 = array(1,2,3); ?>
$vec_2 = array(1,2,3);
$vec_3 = array(0=>1, 1=>2, 2=>3); Output:
$vec_4 = array(12=>1, 3=>2, 4=>3);
$vec_5 = array(1=>2, 0=>1, 2=>3);
var_dump($vec_1==$vec_2); //true
var_dump($vec_1===$vec_2); //true
var_dump($vec_1!=$vec_2); //false
The is_array () Function.
var_dump($vec_1!==$vec_2); //false
Calling the is_array () function on a
echo "<BR>";
variable returns true if that variable holds
var_dump($vec_2==$vec_3); //true
an array, and false if isn't.
var_dump($vec_2===$vec_3); //true
var_dump($vec_2!=$vec_3); //false
<?php
var_dump($vec_2!==$vec_3); //false
$vec_1 = array(1,2,3,4,5,6,7,8);
?>
$vec_2 = 123;
if(is_array($vec_1))
Output:
echo "<BR>vec_1 is an array";
else
echo "<BR>vec_1 is not an array";
if(is_array($vec_2))
echo "<BR>vec_2 is an array";
Example else
echo "<BR>vec_2 is not an array";
<?php ?>
echo "<BR>";
var_dump($vec_2==$vec_4); //false Output:
var_dump($vec_2===$vec_4); //false
var_dump($vec_2!=$vec_4); //true
var_dump($vec_2!==$vec_4); //true
echo "<BR>";
var_dump($vec_2==$vec_5); //true
var_dump($vec_2===$vec_5); //false
The isset () Function
Calling the isset () function can tell us if a The isset () function doesn't return true
specific key already exists in our array... or for array keys that were set together with
not. null as its value.
Output:
<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(array_key_exists('a',$vec)) echo
"<BR>'a' key exists";
if(array_key_exists('b',$vec)) echo
"<BR>'b' key exists";
if(array_key_exists('c',$vec)) echo
"<BR>'c' key exists";
if(array_key_exists('d',$vec)) echo
"<BR>'d' key exists";
if(array_key_exists('e',$vec)) echo
"<BR>'e' key exists";
?>
Output:
The array_reverse () Function
This function returns a new array, which is
the result of reversing the order of a given
one.
<?php current ()
$vec_1 =
array("a","b","c","d","f","g","h"); - gets the current element's value.
echo "<BR>before...<BR>";
var_dump($vec_1); key ()
$vec_2 = array_reverse($vec_1);
echo "<BR>after...<BR>"; - gets the current element's key.
var_dump($vec_2);
?> <?php
$vec =
Output: array("a","b","c","d","f","g","h");
reset($vec);
while(key($vec)!==null)
{
echo key($vec)." is the key and
".current($vec)." is the value<BR>";
next($vec);
}
?>
Output:
reset () to finish.
- resets the pointer to the array initial foreach (___ as ___ => ___)
position. {
…
next () …
…
- moves the pointer to the next element. }
Output:
<?php
$vec =
array('moshe','david','michael','mike');
foreach($vec as $key_var =>
$value_var)
{ The array_combine () Function
echo "<BR>$key_var : $value_var"; The array_combine (array $keys, array
} $values) function receives two arrays
?> and creates a new array. The keys are the
values of the first array elements. The
Output: values are the values of the second array
elements.
<?php
$values_vec =
array('moshe','david','michael','mike');
$keys_vec =
The following is an alternative syntax for array('mosh','dav','mich','mik');
using the foreach. $vec =
array_combine($keys_vec,$values_vec
construct );
print_r($vec);
foreach (___ as ___) ?>
{
… Output:
…
…
}
Output:
<?php
$japan_cars =
array("T" => "Toyota", "M" => "Mazda",
"S" => "Suzuki", "Y" => "Yamaha");
$usa_cars =
array("C" => "Chevrolet", "P" =>
"Pontiac", "C" => "Cryzler");
echo "<P>before ...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
sort($japan_cars);
asort($usa_cars);
echo "<P>after...<BR>";
var_dump($japan_cars);
echo "<BR>"; Both sort () and asort () allows passing a
var_dump($usa_cars); second optional parameter, that configures
?> the operation. This second optional
parameter can be one of the following
Output: possibilities:
SOFT_REGULAR
SORT_NUMERIC
SORT_STRING
rsort () function
Array Shuffle
Calling the shuffle () function will
scramble arrays' elements in a randomize
order.
Output:
Arrays as Stacks
The array_push () and array_pop ()
functions enable us to use an array as a
stack.
int array_push (array &$array, mixed
$var [, mixed $...])
This function pushes the passed values
onto the end of the array. The array's
length is increased by the number of the
passed variables. This function returns the
number of elements, the array has.
mixed array_pop (array &$array)
This function returns the last value of the
array and shorten its length by one.
Arrays as Sets
The array_intersect () function returns
an array containing all the values of
array1 that are present in all other arrays.
The keys are preserved.
<?php
define('IMAGE_TYPES', ['jpg', 'jpeg',
Array Dereferencing 'png', 'gif']);
foreach(IMAGE_TYPES as $v) {
- As of PHP 5.5 it is possible to echo "<h2>".$v."</h2>";
dereference the array directly. }
echo "<h1>".IMAGE_TYPES[0]."</h1>";
<?php ?>
echo ["david","anat","limor","ilana"][0];
?> Output:
Result: david
The ?? Operator
The ?? operator, that was introduced in
PHP 7, is also known as the isset ternary
operator, is a shorthand notation for
performing isset () checks in the ternary
operator.
Example
<?php
function writeMsg() {
echo "Hello world!";
} The following example has a function
writeMsg(); // call the function with two arguments ($fname and
?> $year):
Output: Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year
<br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978"); In the following example we try to send
familyName("Kai Jim", "1983"); both a number and a string to the function,
?> but here we have added the strict
declaration:
Output:
Example
Example
You can specify a different return type,
<?php declare(strict_types=1); // strict than the argument types, but make sure
requirement the return is the correct type:
function sum(int $x, int $y) {
$z = $x + $y; Example
return $z;
} <?php declare(strict_types=1); // strict
echo "5 + 10 = " . sum(5, 10) . "<br>"; requirement
echo "7 + 13 = " . sum(7, 13) . "<br>"; function addNumbers(float $a, float $b)
echo "2 + 4 = " . sum(2, 4); : int {
?> return (int)($a + $b);
}
Output: echo addNumbers(1.2, 5.2);
?>
Output:
<body> </body>
</html>
<?php
/* Defining a PHP Function */ This will display following result –
function writeMessage() {
echo "You are really a nice person, Output:
Have a nice time!";
} Sum of the two numbers is : 30
printMe("This is test");
- is used to aggregate a series of similar
printMe();
items together, arranging and
?>
dereferencing them in some specific way.
</body>
• Each member of the array index
</html>
references a corresponding value and can
be a simple numerical reference to the
This will produce following result –
value’s position in the series, or it could
have some direct correlation to the value.
Output:
• PHP array does not need to declare how
This is test
many elements that the array variable
have.
Dynamic Function Calls
It is possible to assign function names as • Array index in PHP can be also called as
strings to variables and then treat these array keys.
variables exactly as you would the
function name itself. Following example • Array can be used as ordinary array
depicts this behaviour. same as in C and C++ arrays.
Syntax
foreach($arr as $value){
//do something with $value
variable
}
foreach($arr as $key => $value){
//do something with $key
and/or $value variable
}
Output:
foreach($person as $value){
echo "$value <br/>"; keeps the same
} key
echo "<p/>"; ksort($array) Sorts by key
foreach($person as $key => krsort($array) Sorts by key in
reverse order
$value){
usort($array, Sorts by a function
echo "$key: $value <br/>"; functionname)
}
?>
PHP USER DEFINED FUNCTIONS
Functions
Predefined functions
Output:
- functions that are built-in into PHP to
perform some standard operations
Syntax
function name(param){
//code to be executed by the
function
}
Arrays: Sorting
Where
Function Description
sort($array) Sort by value;
function
assign new
numbers as the
keys - is the keyword used to declare a function
rsort($array) Sorts by value in
reverse order; name
assign new
number as the - is the name of the function or function
keys identifier
asort($array) Sorts by value;
keeps the same
key
arsort($array) Sorts by value in
reverse order;
param Output:
Output:
Local Variables
Example function that returns a value
- is declared inside a function and is only
function qoutient($x, $y){ available within the function in which it is
return $x/$y; declared.
}
Static Variables
function remark($grade){
if($grade >= 75){ - is used to retain the values calls to the
return true; same function.
} else{
Example:
return false;
}
<?php
}
$str = "This is global
variable";
printf("The qoutient is
function f(){
%.2f<br/>", qoutient(7,3));
echo "function f () was
if(remark(80)){
called<br>";
echo "passed";
echo "$str<br>";
} else {
}
echo "failed";
f();
}
?>
Output:
Example:
Output: <?php
$str = "This is global
variable";
function f(){
global $str;
Global Variables
echo "function f () was
called<br>";
- is one that declared outside a function
echo "$str<br>";
and is available to all parts of the program.
}
f();
?>
echo $str;
?>
Output:
Output:
Example:
<?php MODULE 4
function f(){
PHP Predefined Functions – Constants,
Files and Mathematical Functions
$str = "This is local
variable";
} PHP PREDEFINED FUNCTIONS
f();
echo "Displaying local variable: Using Constant
" ;
echo $str; define () functions.
?>
- used to declare constants. A constant
can only be assigned a scalar value, like a
string or a number. A constant’s value
cannot be changed.
Syntax:
define(‘NAME’,’value’);
Output:
Example:
<?php
define('MAX_VALUE', 10);
Example:
for($i=5; $i<MAX_VALUE;$i++){
echo $i." ";
<?php
}
function f(){
//MAX_VALUE = 20; is invalids
global $str;
?>
$str = "This is local
variable";
}
f();
echo "Displaying local variable:
" ;
redefinitions, variable reassignments, and
other possible problems.
Syntax:
include(“filename.inc”);
include_once(“filename.inc”);
Output: require(“filename.inc”);
require_once(“filename.inc”);
You may write the file with an extension require() function (file not found)
name of .inc rather than .php to serve as a
fragment of your program code. Example:
MATHEMATICAL FUNCTION:
rand () function
Output:
- used to generate random integers
- syntax
int rand(void)
int rand(int $min, int $max)
include() function(file exists)
ceil () function.
Example:
- returns the next highest integer by
rounding the value upwards
<html>
- syntax
<head>
float ceil(float $value)
<title></title>
<meta http-equiv="Content-
floor () function
Type" content="text/html; charset-
UTF-8"> - returns the next lowest integer by
</head> rounding the value downwards
<body> - syntax
<?php float floor(float $value)
include("header.inc")?>
<h4>Content</h4> min () function
The quick brown fox jumps
over the lazy dog near the bank of - Return the smallest value
the rivers - syntax
</body> mixed min(array $values) mixed
</html> min(mixed $values1, mixed
$values2[,mixed $...])
max () function
Example:
<?php
for($i=0;$i < 5; $i++){
$xgen[] = rand();
Output:
}
echo "x values: ";
foreach ($xgen as $num){
echo $num." ";
}
echo "<br/>";
echo "min: ".min($xgen)." max:
".max($xgen); MATHEMATICAL FUNCTION
echo "<br/>";
for($i=0; $i<5; $i++){
number_format () function
$ygen[] = rand(5,10);
}
- Format a number with grouped thousand
echo "y values: ";
- syntax
foreach($ygen as $num){
string number_format (
echo $num." "; float $number
} [, int $decimals = 0 ] )
echo "<br />";
echo "min: ".min($ygen)." max string number_format (
".max($ygen); float $number ,
echo "<br />"; int $decimals = 0 ,
echo "ceil(3.01): string $dec_point = '.' ,
".ceil(3.01)."<br/>"; string $thousands_sep = ',' )
echo "floor(3.91):
".floor(3.91)."<br/>"; Example:
?>
<?php
$price = 217795.75;
echo
number_format($price)."<br>";
echo number_format($price, 2,
'.', '')."<br>";
echo number_format($price, 2,
'.',',')."<br>";
?> foreach($fruitArr as $fruit)
echo $fruit." ";
$fruitStr = implode(",",
$fruitArr);
echo "<p/>Fruit string
(implode) : $fruitStr";
Output:
unset ($fruitArr);
echo "<p/> Fruit list
(unset) <pre>"; print_r($fruitArr);
echo "</pre>";
unset function
implode function.
FUNCTION FOR STRING
- join array elements to form a string MANIPULATION:
- syntax:
string implode ( string $glue ,
strlen function
array $pieces )
string implode ( array $pieces )
- return the value length of a string
- syntax:
unset(), explode(), implode()
int strlen (string $string)
Example:
strpos function
<?php
- find the position of the first occurrence of
$fruitArr = array('orange', a substring in a given string
'apple', 'grapes', 'mango',
'banana');
- syntax: printf("Sub String \"fox
int strpos ( string $haystack , jumps\": %s <br/>", substr($str, 16,
mixed $needle [, int $offset = 0 9));
]) ?>
strrev function
strtoupper function
strip_tags () function
<?php
$str = "the quick bron fox
jumps...";
echo ucfirst($str)."<br/>";
echo ucwords($str)."<br/>";
$str = " sample
string ";
echo "<pre>"; var_dump($str);
echo "</pre>";
$str = ltrim($str);
echo "<pre>"; var_dump($str); DATE MANIPULATION
echo "</pre>";
$str = rtrim($str); date () Function
echo "<pre>"; var_dump($str);
echo "</pre>"; - used to format a local time or date
$str = " sample - returns a string formatted according to
string "; the given format string.
echo "<pre>"; var_dump($str); - syntax:
echo "</pre>"; string date ( string $format [, int
$str = trim($str); $timestamp = time() ] )
echo "<pre>"; var_dump($str);
Format Description Example
echo "</pre>"; character returned
$str = "<p>paragraph</p><hr/><a values
href='#'>link</a>"; DAY
d Day of the month, 2 01 to 31
$strA = strip_tags($str); digits with leading zeros
echo "<pre>"; var_dump($strA); D A textual representation Mon
echo "</pre>"; of a day, three letters through
Sun
$strB = strip_tags($str, j Day of the month 1 to 31
'<a><p>'); without leading zeros
l A full textual Sunday Y A full numeric Examples:
representation of the through representation of a year, 1999 or
day of the week Saturday 4 digits 2003
N ISO-8601 numeric 1 (for y A two digit representation Examples:
representation of the Monday) of a year 99 or 03
day of the week (added through 7
in PHP 5.1.0) (for Format Description Example
Sunday) character returned
S English ordinal suffix for st, nd, rd values
the day of the month, 2 or th. TIME
characters Works
a Lowercase Ante am or pm
well with j
meridiem and Post
w Numeric representation 0 (for meridiem
of the day of the week Sunday)
A Uppercase Ante AM or PM
through 6
meridiem and Post
(for
meridiem
Saturday)
B Swatch Internet time 000 through
z The day of the year 0 through
999
(starting from 0) 365
g 12-hour format of an 1 through 12
W ISO-8601 week number Example:
hour without leading
of year, weeks starting 42 (the
zeros
on Monday 42nd week
G 24-hour format of an 0 through 23
in the
hour without leading
year)
zeros
h 12-hour format of an 01 through12
Format Description Example hour with leading
character returned zeros
values H 24-hour format of an 00 through 23
MONTH hour with leading
F A full textual January zeros
representation of a through i Minutes with leading 00 to 59
month, such as December zeros
January or March s Seconds, with leading 00 through 59
m Numeric 01 zeros
representation of a through u Microseconds Example:
month, with leading 12 654321
zeros
M A short textual Jan
Format Description Example
representation of a through
character returned
month, three letters Dec
values
n Numeric 1 through
TIMEZONE
representation of a 12
month, without leading e Timezone identifier Examples:
zeros UTC, GMT,
Atlantic/Azor
t Number of days in the 28
es
given month through
31 I Whether or not the 1 if Daylight
date is in daylight Saving Time,
saving time 0 otherwise.
Format Description Example O Difference to Example:
character returned Greenwich time +0200
values (GMT) in hours
YEAR P Difference to Example:
L Whether it’s a leap year 1 if it is a Greenwich time +02:00
leap year, (GMT) with colon
0 between hours and
otherwise. minutes
o ISO-8601 year number. Examples: T Timezone Example:
This has the same value 1999 or abbreviation EST, MDT…
as Y, except that if the 2003 z Timezone offset in -43200
ISO week number (W) seconds. The offset through
belongs to the previous for timezones west of 50400
or next year, that year is UTC is always
used instead. negative, and for
those east of UTC is
always positive.
[, int $second = date("s")
[, int $month = date("n")
Format Description Example [, int $day = date("j")
charact returned values
[, int $year = date("Y")
er
[, int $is_dst = -1 ]]]]]]] )
FULL DATE/TIME
c ISO 8601 2004-02-
date 12T15:19:21+00 strtotime () function
:00)
r >> RFC Example: Thu, - parse any English textual datetime
2822 21 Dec 2000 description into a Unix timestamp
formatted 16:01:07 + 0200 - syntax:
date int strtotime ( string $time
U Seconds See also time () [, int $now = time() ] )
since the
Unix Epoch SUPPLEMENTARY
(January 1,
1970,
00:00:00 Constant in PHP
GMT) 1. Constants are PHP container that
remain constant and never change
PHP: Documentation 2. Constants are used for data that is
unchanged at multiple places within our
Example: program.
3. Variables are temporary storage while
<?php Constants are permanent.
echo date("l"); 4. Use Constants for values that remain
echo "<br/>"; fixed and referenced multiple times.
echo date('l jS \of F Y h:i:s
A'); Rules for defining constant.
?> 1. Constants are defined using PHP's
define () function, which accepts two
arguments: The name of the constant, and
its value.
Syntax:
<?php
mktime () function
define('ConstName', 'value');
?>
- get the unix timestamp (January 1,
1970) for a given date. (With strict
notice) Valid and Invalid Constant declaration:
- same as time () function (without strict
notice) <?php
- syntax:
int mktime ([ int $hour = date("H") //valid constant names
[, int $minute = date("i") define('ONE', "first value");
define('TWO', "second value"); Subtraction of two numbers using
define('SUM 2',ONE+TWO); constant
<h2>USD/EUR Currency
Conversion</h2>
<?php
PHP Math Functions
//define exchange rate
//1.00 USD= 0.80 EUR Function Description
define('EXCHANGE_RATE',0.80); abs() Returns the absolute
(positive) value of a
//define number of dollars number
$dollars=150; acos() Returns the arc
cosine of a number
//perform conversion and print result acosh() Returns the inverse
$euros=$dollars*EXCHANGE_RATE; hyperbolic cosine of a
number
echo "$dollars USD is equivalent to asin() Returns the arc sine
:$euros EUR"; of a number
?> asinh() Returns the inverse
hyperbolic sine of a
number
Output
atan() Returns the arc
tangent of a number
USD/EUR Currency in radians
atan2() Returns the arc
Conversion tangent of two
variables x and y
150 USD is equivalent to :120 EUR. atanh() Returns the inverse
hyperbolic tangent of
if you have been following along, the script a number
should be fairly easy to understand. It base_convert() Converts a number
begins by defining a constant named from one number
"EXCHANGE_RATE" which surprise, base to another
surprise stores the dollar-to-euro bindec() Converts a binary
exchange rate (assumed here at 1.00 number to a decimal
number
USD to 0.80 EUR). Next, it defines a
ceil() Round a number up
variable named "$dollars" to hold the
to the nearest integer
number of dollars to be converted, and cos() Returns the cosine of
then it performs an arithmetic operation a number
using the * operator, the "$dollars" cosh() Returns the
variable, and the "EXCHANGE_RATE" hyperbolic cosine of a
constant to return the equivalent number number
of euros. This result is then stored in a decbin() Converts a decimal
new variable named "$euros" and printed number to a binary
to the Web page. number
dechex() Converts a decimal
number to a
PHP Math Introduction
hexadecimal number
The math functions can handle values
decoct() Converts a decimal
within the range of integer and float types. number to an octal
number
Installation deg2rad() Converts a degree
The PHP math functions are part of the value to a radian
PHP core. No installation is required to value
use these functions. exp() Calculates the
exponent of e
expm1() Returns exp(x) – 1
floor() Rounds a number octdec() Converts an octal
down to the nearest number to a decimal
integer number
fmod() Returns the pi() Returns the value of
remainder of x/y PI
getrandmax() Returns the largest pow() Returns x raised to
possible value the power of y
returned by rand() rad2deg() Converts a radian
hexdec() Converts a value to a degree
hexadecimal number value
to a decimal number rand() Generates a random
hypot() Calculates the integer
hypotenuse of a right- round() Rounds a floating-
angle triangle point number
intdiv() Performs integer sin() Returns the sine of a
division number
is_finite() Checks whether a sinh() Returns the
value is finite or not hyperbolic sine of a
is_infinite() Checks whether a number
value is infinite or not sqrt() Returns the square
is_nan() Checks whether a root of a number
value is ‘not-a- srand() Seeds the random
number’ number generator
lcg_value() Returns a pseudo tan() Returns the tangent
random number in a of a number
range between 0 and tanh() Returns the
1 hyperbolic tangent of
log() Returns the natural a number
logarithm of a number
log10() Returns the base-10 PHP Predefined Math Constants
logarithm of a number
log1p() Returns Constant Value Descri
log(1+number) ption
max() Returns the highest INF INF The
value in an array, or infinite
the highest value of M_E 2.718281828459 Return
0452354 se
several specified M_EULER 0.577215664901 Return
values 53286061 s Euler
min() Returns the lowest consta
value in an array, or nt
the lowest value of M_LNPI 1.144729885849 Return
40017414 s the
several specified natural
values logarith
mt_getrandmax() Returns the largest m of PI:
possible value log_e(p
i)
returned by mt_rand() M_LN2 0.693147180559 Return
mt_rand() Generates a random 94530942 s the
integer using natural
Mersenne Twister logarith
algorithm m of 2:
log_e 2
mt_srand() Seeds the Mersenne M_LN10 2.302585092994 Return
Twister random 04568402 s the
number generator natural
logarith
m of PHP_ROUND_HA 3 Round
10: LF_EVEN halves
log_e to even
10 number
M_LOG2E 1.442695040888 Return s
9634074 s the PHP_ROUND_HA 4 Round
base-2 LF_ODD halves
logarith to odd
m of E: number
log_2 e s
M_LOG10E 0.434294481903 Return
25182765 s the
base- PHP Constants
10
logarith
m of E: Constants are either identifiers or simple
log_10 names that can be assigned any fixed
e
M_PI 3.141592653589 Return
values. They are similar to a variable
79323846 s Pi except that they can never be changed.
M_PI_2 1.570796326794 Return They remain constant throughout the
89661923 s Pi/2 program and cannot be altered during
M_PI_4 0.785398163397 Return
44830962 s Pi/4 execution. Once a constant is defined, it
M_1_PI 0.318309886183 Return cannot be undefined or redefined.
79067154 s 1/Pi Constant identifiers should be written in
M_2_PI 0.636619772367 Return
58134308 s 2/Pi
upper case following the convention. By
M_SQRTPI 1.772453850905 Return default, a constant is always case-
51602729 s the sensitive, unless mentioned. A constant
square
root of
name must never start with a number. It
PI: always starts with a letter or underscores,
sqrt(pi) followed by letter, numbers or underscore.
M_2_SQRTPI 1.128379167095 Return It should not contain any special
51257390 s
2/squar characters except underscore, as
e root mentioned.
of PI:
2/sqrt(p
i) Creating a PHP Constant
M_SQRT1_2 0.707106781186 Return The define () function in PHP is used to
54752440 s the
square create a constant as shown below:
root of
½: Syntax:
1/sqrt(2
)
M_SQRT2 1.414213562373 Return define(name, value, case_insensitive)
09504880 s the
square
root of
The parameters are as follows:
2:
sqrt(2) name:
M_SQRT3 1.732050807568 Return
87729352 s the
square - The name of the constant.
root of
3: value:
sqrt(3)
PHP_ROUND_HA 1 Round
LF_UP halves - The value to be stored in the constant.
up
PHP_ROUND_HA 2 Round
LF_DOWN halves
down
Example:
case_insensitive:
Example:
<?php
define("WELCOME",
"GeeksforGeeks!!!");
Output:
GeeksforGeeks
Constants vs Variables ceil() Next Higher integer
• A constant, once defined can never be after rounding
undefined but a variable can be easily cos() Cos value of Radian
input
undefined.
cosh() Hyperbolic cosine
decbin() Binary equivalent of
• There is no need to use dollar sign ($) Decimal number
before constants during assignment but dechex() Hex equivalent of
while declaring variables we use a dollar Decimal number
sign. decoct() Octal equivalent of
Decimal number
• A constant can only be defined using a deg2rad() Convert Degree value
define () function and not by any simple to Radian
assignment. exp() Value of e raised to
the power of input
• Constants don’t need to follow any value
variable scoping rules and can be defined expm1() equivalent to
anywhere. ‘exp(arg) – 1’
floor() nearest lower integer
fmod() reminder (modulo) of
PHP Math functions a division
Mathematics (or math ) functions are getrandmax() largest random value
frequently used in our scripts. There are hexdec() Hexadecimal to
PHP math functions to take care of decimal
addition subtraction multiplication and hypot() hypotenuse of a right-
many other mathematical requirements. angle triangle
intdiv() integer quotient of the
We will discuss these math functions and division (PHP7)
try to develop some sample codes on is_finite() Checking legal finite
these to further understand on how to use number
these functions. is_infinite() Checking whether a
value is infinite
Function Description is_nan() Checks whether a
abs() Absolute value of a value is not a number
number lcg_value() pseudo random
acos() Arc Cosine value of number generator
input log() Log value with
acosh() Inverse hyperbolic different Base
cosine of input log10() Log value with Base
asin() Arc Sin value of input 10
asinh() Inverse hyperbolic log1p() Log value with input
sine of input added by 1
atan() Arc tangent value of max() Maximum value from
input array or group
atan2() Arc tangent of two min() Minimum value from
inputs array or group
atanh() Inverse hyperbolic mt_getrandmax() largest possible
tangent value of input random value
base_convert() Convert number from mt_rand() random value
one base to other generator
bindec() Decimal equivalent of mt_srand() Seeds random value
Binary string generator
octdec() Convert Octal to
Decimal Number
PI() Constant value PI() & column in the
M_PI input array
POW() Exponential value of a array_combine() Creates an
Base array by
round() Rounded value of a using the
number elements
rand() Generates a random from one
integer “keys” array
random_init() cryptographic random and one
integer generator “values”
(PHP 7) array
rad2deg() Convert radian to array_count_values() Counts all
degree the values of
sin() Sin value of Radian an array
input array_diff() Compare
sinh() Hyperbolic sine value arrays, and
sqrt() square root of number returns the
tan() Tangent value of differences
Radian input (compare
tanh() Hyperbolic tangent values only)
value array_diff_assoc() Compare
arrays, and
returns the
PHP ARRAY INTRODUCTION differences
(compare
The array functions allow you to access keys and
and manipulate arrays. values)
Simple and multi-dimensional arrays are array_diff_key() Compare
supported. arrays and
returns the
differences
Installation (compare
The array functions are part of the PHP keys only)
core. There is no installation needed to array_diff_uassoc() Compare
use these functions. arrays, and
returns the
differences
PHP Array Functions
(compare
keys and
Function Description values, using
array() Creates an a user-
array defined key
array_change_key_ca Changes all comparison
se() keys in an function)
array to array_diff_ukey() Compare
lowercase or arrays, and
uppercase returns the
array_chunk() Splits an differences
array into (compare
chunks of keys only,
arrays using a user-
array_column() Returns the defined key
values from a comparison
single function)
array_fill() Fills an array defined key
with values comparison
array_fill_keys() Fills an array function)
with values, array_key_exists() Checks if the
specifying specified key
keys exists in the
array_filter() Filters the array
values of an array_keys() Returns all
array using a the keys of
callback an array
function array_map() Sends each
array_flip() Flips/Exchan value of an
ges all keys array to a
with their user-made
associated function,
values in an which returns
array new values
array_intersect() Compare array_merge() Merges one
arrays, and or more
returns the arrays into
matches one array
(compare array_merge_recursiv Merges one
values only) e() or more
array_intersect_assoc Compare arrays into
() arrays and one array
returns the recursively
matches array_multisort() Sorts multiple
(compare or multi-
keys and dimensional
values) arrays
array_intersect_key() Compare array_pad() Inserts a
arrays, and specified
returns the number of
matches items, with a
(compare specified
keys only) value, to an
array_intersect_uasso Compare array
c() arrays, and array_pop() Deletes the
returns the last element
matches of an array
(compare array_product() Calculates
keys and the product
values, using of the values
a user- in an array
defined key array_push() Inserts one
comparison or more
function) elements to
array_intersect_ukey() Compare the end of an
arrays, and array
returns the array_rand() Returns one
matches or more
(compare random keys
keys only, from an array
using a user-
array_reduce() Returns an (compare
array as a values only,
string, using using a user-
a user- defined key
defined comparison
function function)
array_replace() Returns the array_udiff_assoc() Compare
values of the arrays, and
first array returns the
with the differences
values from (compare
following keys and
arrays values, using
array_replace_recursi Replaces the a built-in
ve() values of the function to
first array compare the
with the keys and a
values from user-defined
following function to
arrays compare the
recursively values)
array_reverse() Returns an array_udiff_uassoc() Compare
array in the arrays, and
reverse order returns the
array_search() Searches an differences
array for a (compare
given value keys and
and returns values, using
the key two user-
array_shift() Removes the defined key
first element comparison
from an functions)
array, and array_uintersect() Compare
returns the arrays, and
value of the returns the
removed matches
element (compare
array_slice() Returns values only,
selected using a user-
parts of an defined key
array comparison
array_splice() Removes function)
and replaces array_uintersect_asso Compare
specified c() arrays, and
elements of returns the
an array matches
array_sum() Returns the (compare
sum of the keys and
values in an values, using
array a built-in
array_udiff() Compare function to
arrays, and compare the
returns the values)
differences
array_unintersect_uas Compare elements in
soc() arrays, and an array
returns the current() Returns the
matches current
(compare element in an
keys and array
values, using each() Deprecated
two user- from PHP
defined key 7.2. Returns
comparison the current
functions) key and
array_unique() Removes value pair
duplicate from an array
values from end() Sets the
an array internal
array_unshift() Adds one or pointer of an
more array to its
elements to last element
the beginning extract() Imports
of an array variables into
array_values() Returns all the current
the values of symbol table
an array from an array
array_walk() Applies a in_array() Checks if a
user function specified
to every value exists
member of in an array
an array key() Fetches a
array_walk_recursivel Applies a key from an
y() user function array
recursively to krsort() Sorts an
every associative
member of array in
an array descending
arsort() Sorts an order,
associative according to
array in the key
descending ksort() Sorts an
order, associative
according to array in
the value ascending
asort() Sorts an order,
associative according to
array in the key
ascending list() Assigns
order, variables as
according to if they were
the value an array
compact() Create array natcasesort() Sorts an
containing array using a
variables and case
their values insensitive
count() Returns the “natural
number of
order” user-defined
algorithm comparison
natsort() Sorts an function
array using a
“natural PHP String Functions
order”
algorithm
In this chapter we will look at some
next() Advance the
internal array commonly used functions to manipulate
pointer of an strings.
array
pos() Alias of strlen()
current()
prev() Rewinds the – Return the Length of a String
internal array - The PHP strlen() function returns the
pointer length of a string.
range() Creates an
array Example
containing a
range of Return the length of the string "Hello
elements world!":
reset() Sets the
internal
<?php
pointer of an
array to its echo strlen("Hello world!"); // outputs
first element 12
rsort() Sorts an ?>
indexed array
in Output:
descending
order
shuffle() Shuffles an
array
sizeof() Alias of
count() str_word_count()
sort() Sorts an
indexed array - Count Words in a String
in ascending
order
The PHP str_word_count() function
uasort() Sorts an
counts the number of words in a string.
array by
values using
a user- Example
defined
comparison Return the length of the string "Hello
function world!":
uksort() Sorts an
array by keys <?php
using a user- echo strlen("Hello world!"); // outputs
defined 12
comparison ?>
function
usort() Sorts an Output:
array using a
Tip: The first character position in a string
is 0 (not 1).
strrev() str_replace()
The PHP strrev() function reverses a The PHP str_replace() function replaces
string. some characters with some other
characters in a string.
Example
Example
Reverse the string "Hello world!":
Replace the text "world" with "Dolly":
<?php
echo strrev("Hello world!"); // outputs <?php
!dlrow olleH echo str_replace("world", "Dolly",
?> "Hello world!"); // outputs Hello
Dolly!
Output: ?>
Output:
strpos()
m
Get a Time
- Represents a month (01 to 12) Here are some characters that are
commonly used for times:
Y
H
- Represents a year (in four digits)
- 24-hour format of an hour (00 to 23)
l (lowercase ‘L’)
h
- Represents the day of the week
- 12-hour format of an hour with leading
Other characters, like"/", ".", or "-" can zeros (01 to 12)
also be inserted between the characters to
add additional formatting. i
The example below formats today's - Minutes with leading zeros (00 to 59)
date in three different ways:
s
Example
- Seconds with leading zeros (00 to 59)
<?php
echo "Today is " . date("Y/m/d") . a
"<br>";
echo "Today is " . date("Y.m.d") . - Lowercase Ante meridiem and Post
"<br>"; meridiem (am or pm)
echo "Today is " . date("Y-m-d") .
"<br>"; The example below outputs the current
echo "Today is " . date("l"); time in the specified format:
?>
Example
Output:
<?php
echo "The time is " . date("h:i:sa");
?>
Output: Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d
Get Your Time Zone h:i:sa", $d);
If the time you got back from the code is ?>
not correct, it's probably because your
server is in another country or set up for a Output:
different timezone.
<?php Syntax
date_default_timezone_set("America/N
ew_York"); strtotime(time, now)
echo "The time is " . date("h:i:sa");
?> The example below creates a date and
time from the strtotime() function:
Output:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d
Create a Data With mktime()
h:i:sa", $d);
The optional timestamp parameter in the
?>
date () function specifies a timestamp. If
omitted, the current date and time will be
Output:
used (as in the examples above).
<?php
$lamborghinis = array("Urus",
"Huracan", "Aventador");
The example below outputs the number
echo "Size of the array is: ".
of days until 4th of July:
sizeof($lamborghinis);
$lamborghinis = array("Urus",
?> "Huracan", "Aventador");
Output: <?php
$lamborghinis = array("Urus",
Array "Huracan", "Aventador");
print_r($merged); print_r($merged);
?> ?>
Output: Output:
Array ( Array (
[Suzuki] => Baleno [0] => Baleno
[Skoda] => Fabia [1] => Fabia
[Hyundai] => i20 [2] => i20
[Tata] => Tigor [3] => Tigor
[0] => Vinod [4] => Vinod
[1] => Javed [5] => Javed
[2] => Navjot [6] => Navjot
[3] => Samuel [7] => Samuel
) )
array_values($arr) array_keys($arr)
- In an array, data is stored in form of key- Just like values, we can also extract just
value pairs, where key can be numerical the keys from an array. Let's use this
(in case of indexed array) or user- function to extract the keys from the array
defined strings (in case of associative $merged.
array) and values.
<?php
- If we want to take all the values from our //getting only the keys
array, without the keys, and store them in $keys = array_values($merged);
array_push($lamborghinis, "Estoque");
print_r($keys);
?> print_r($lamborghinis);
?>
Output:
Output:
Array (
[0] => Suzuki Array (
[1] => Skoda [0] => Urus
[2] => Hyundai [1] => Huracan
[3] => Tata [2] => Aventador
[4] => 0 [3] => Estoque
[5] => 1 )
[6] => 2
[7] => 3 array_shift($arr)
)
- This function can be used to remove/shift
array_pop($arr) the first element out of the array. So, it is
just like array_pop() function but different
- This function removes the last element of in terms of the position of the element
the array. Hence it can be used to remove removed.
one element from the end.
<?php
<?php $lamborghinis = array("Urus",
$lamborghinis = array("Urus", "Huracan", "Aventador");
"Huracan", "Aventador");
// removing the first element
// removing the last element array_shift($lamborghinis);
array_pop($lamborghinis);
print_r($lamborghinis);
print_r($lamborghinis); ?>
?>
Output:
Output:
Array (
Array ( [0] => Huracan
[0] => Urus [1] => Aventador
[1] => Huracan )
)
Similar to this, we have another function
array_push($arr, $val) array_unshift($arr, $val) to add a new
value($val) at the start of the array(as the
- This function is the opposite of the first element).
array_pop() function. This can be used to
add a new element at the end of the array. sort($arr)
<?php Array (
function addOne($val) { [Baleno] => Suzuki
// adding 1 to input value [Fabia] => Skoda
return ($val + 1); [i20] => Hyundai
} [Tigor] => Tata
)
$numbers = array(10, 20, 30, 40, 50);
array_reverse($arr)
// using array_map to operate on all the
values stored in array - This function is used to reverse the order
of elements, making the first element last
and last element first, and similarly array_slice($arr, $offset, $length)
rearranging other array elements.
- This function is used to create a subset
<?php of any array. Using this function, we define
$num = array(10, 20, 30, 40, 50); the starting point ($offset, which is the
// printing the array after reversing it array index from where the subset
print_r(array_reverse($num)); starts) and the length (or, the number of
?> elements required in the subset,
starting from the offset).
Output:
- Let's take an example,
Array (
[0] => 50 <?php
[1] => 40 $colors = array("red", "black", "blue",
[2] => 30 "green", "white", "yellow");
[3] => 20
[4] => 10 print_r(array_slice($colors, 2, 3));
) ?>
array_rand($arr) Output:
\n
\r
Example <?php
$my_str = 'You can do anything, but
<?php not everything.';
$my_str = 'If the facts do not fit the
theory, change the facts.'; // Display reversed string
echo strrev($my_str);
// Display replaced string ?>
echo str_replace("facts", "truth",
$my_str); The output of the above code will be:
?>
Output:
The output of the above code will be:
.gnihtyreve ton tub ,gnihtyna od nac uoY
Output:
PHP Date Function
If the truth do not fit the theory, change the
PHP date function is an in-built function
truth.
that simplify working with date data types.
The PHP date function is used to format
You can optionally pass the fourth
a date or time into a human readable
argument to the str_replace() function to
format. It can be used to display the date
know how many times the string
of article was published. record the last
replacements was performed, like this.
updated a data in a database.
Example
In this tutorial, you will learn-
• PHP Date Syntax & Example
<?php
• What is a TimeStamp?
$my_str = 'If the facts do not fit the
• Getting a list of available time zone
theory, change the facts.';
identifiers
• PHP set Timezone Programmatically
// Perform string replacement
• PHP Mktime Function
str_replace("facts", "truth", $my_str,
• PHP Date function
$count);
• Time parameters
• Day parameters
// Display number of replacements
• Month Parameters
performed
• Year Parameters
PHP Date Syntax & Example The value returned by the time function
PHP Date the following basic syntax depends on the default time zone.
- is the general format which we want our Assuming you saved the file
output to be i.e. timestamp.php in phptuts folder, browse to
the URL
o “Y-m-d” http://localhost/phptuts/timestamp.php
o “Y”
o “[timestamp]”
- iterates through the numeric array and - is the time zone identifier
prints the values.
The script below displays the time
Assuming you saved the file according to the default time zone set in
list_time_zones.php in phptuts folder, php.ini.
browse to the URL It then changes the default time zone to
http://localhost/phptuts/list_time_zones Asia/Calcutta and displays the time again.
.php
<?php
Output: echo "The time in " .
date_default_timezone_get() . " is " .
date("H:i:s");
date_default_timezone_set("Asia/Calcu
tta");
echo "The time in " .
date_default_timezone_get() . " is " .
date("H:i:s");
?>
Output:
PHP set Timezone Programmatically
The date_default_timezone_set function
allows you to set the default time zone
from a PHP script.
define () functions.
used to declare constants. A constant can
only be assigned a scalar value, like a
string or a number. A constant’s value
cannot be changed.
define(‘NAME’,’value’);
Parameter Description Example
“L” Returns 1 if it’s <?php
a leap year echo You can separate your PHP file and
and 0 if it is date("L") embed it to your html by using PHP
not a leap year ; include functions.
?>
“Y” Returns four <?php Include functions Description
digit year echo include Includes and
format date("Y") evaluates the
; specified file.
?> Generate a
“y” Returns two <?php warning on failure
(2) digits year echo message if file not
format (00 to date("y") found.
99) ; require Performs the same
?> way as the include
function. Generate
Output: a fatal error
message if file not
found stopping the
script
include_once Same as include
function except it
includes the file
Summary only once.
• The date function is used to format the require_once Same as require
function except it
timestamp into a human desired format.
includes the file
only once.
• The timestamp is the number of seconds
between the current time and 1 st Most of the developers used include
January 1970 00:00:00 GMT. It is also functions for their header and footer. Also,
known as the UNIX timestamp. some use this to write their database
connection and so on.
• All date functions use the default time
zone set in the php.ini file You may write the file with an extension
name of .inc rather than .php to serve as a
• The default time zone can also be set fragment of your program code.
programmatically using PHP scripts.
In some scripts, a file might be included
more than once, causing function
redefinitions, variable reassignments, and number_format () function
other possible problems.
- Format a number with grouped thousand
Syntax: - syntax
string number_format (
include(“filename.inc”); float $number
include_once(“filename.inc”); [, int $decimals = 0 ] )
require(“filename.inc”);
require_once(“filename.inc”); string number_format (
float $number ,
MATHEMATICAL FUNCTION: int $decimals = 0 ,
string $dec_point = '.' ,
string $thousands_sep = ',' )
rand () function
unset function
- used to generate random integers
- syntax
- destroys the specified variable
int rand(void)
- syntax:
int rand(int $min, int $max)
void unset ( mixed $var [, mixed
$... ] )
ceil () function.
explode function.
- returns the next highest integer by
rounding the value upwards
- split a string by string
- syntax
- syntax:
float ceil(float $value)
array explode ( string $delimiter
, string $string [, int $limit ] )
floor () function
implode function.
- returns the next lowest integer by
rounding the value downwards
- join array elements to form a string
- syntax
- syntax:
float floor(float $value)
string implode ( string $glue ,
array $pieces )
min () function
string implode ( array $pieces )
- Return the smallest value
strlen function
- syntax
mixed min(array $values) mixed
- return the value length of a string
min(mixed $values1, mixed
- syntax:
$values2[,mixed $...])
int strlen (string $string)
max () function
strpos function
- Return the highest value
- find the position of the first occurrence of
- syntax
a substring in a given string
mixed max(array $values) mixed
- syntax:
max(mixed $values1, mixed
int strpos ( string $haystack ,
$values2[,mixed $...])
mixed $needle [, int $offset = 0
])
strrev function - syntax:
string ltrim ( string $str [, string
- reverse a given string $charlist ] )
- syntax:
string strrev ( string $string ) rtrim () function
- converts string to uppercase - strip HTML and PHP tags from a string.
- syntax: - syntax:
string strtoupper ( string $str ) string strip_tags ( string $str [,
string $allowable_tags ] )
substr function
DATE MANIPULATION
- returns part of a given string
- syntax:
date () Function
string substr ( string $string ,
int $start [, int $length ] )
- used to format a local time or date
- returns a string formatted according to
ucfirst () function
the given format string.
- syntax:
- Make a string’s first character uppercase
string date ( string $format [, int
- syntax:
$timestamp = time() ] )
string ucfirst( string $str )
Format Description Example
ucwords () function character returned
values
- converts string to uppercase DAY
d Day of the month, 2 01 to 31
- syntax: digits with leading zeros
string ucwords ( string $str ) D A textual representation Mon
of a day, three letters through
Sun
trim () function
j Day of the month 1 to 31
without leading zeros
- stripped white spaces or other characters l A full textual Sunday
from the beginning and end of a string. representation of the through
day of the week Saturday
N ISO-8601 numeric 1 (for
- syntax: representation of the Monday)
string trim ( string $str [, string day of the week (added through 7
in PHP 5.1.0) (for
$charlist ] ) Sunday)
S English ordinal suffix for st, nd, rd
ltrim () function the day of the month, 2 or th.
characters Works
well with j
- strip white spaces or other characters w Numeric representation 0 (for
from the beginning of a string. of the day of the week Sunday)
through 6 B Swatch Internet time 000 through
(for 999
Saturday) g 12-hour format of an 1 through 12
z The day of the year 0 through hour without leading
(starting from 0) 365 zeros
W ISO-8601 week number Example: G 24-hour format of an 0 through 23
of year, weeks starting 42 (the hour without leading
on Monday 42nd week zeros
in the h 12-hour format of an 01 through12
year) hour with leading
zeros
Format Description Example H 24-hour format of an 00 through 23
character returned hour with leading
values zeros
MONTH i Minutes with leading 00 to 59
F A full textual January zeros
representation of a through s Seconds, with leading 00 through 59
month, such as December zeros
January or March u Microseconds Example:
m Numeric 01 654321
representation of a through
month, with leading 12 Format Description Example
zeros character returned
M A short textual Jan values
representation of a through TIMEZONE
month, three letters Dec e Timezone identifier Examples:
n Numeric 1 through UTC, GMT,
representation of a 12 Atlantic/Azor
month, without leading es
zeros I Whether or not the 1 if Daylight
t Number of days in the 28 date is in daylight Saving Time,
given month through saving time 0 otherwise.
31 O Difference to Example:
Greenwich time +0200
Format Description Example (GMT) in hours
character returned P Difference to Example:
values Greenwich time +02:00
YEAR (GMT) with colon
L Whether it’s a leap year 1 if it is a between hours and
leap year, minutes
0 T Timezone Example:
otherwise. abbreviation EST, MDT…
o ISO-8601 year number. Examples: z Timezone offset in -43200
This has the same value 1999 or seconds. The offset through
as Y, except that if the 2003 for timezones west of 50400
ISO week number (W) UTC is always
belongs to the previous negative, and for
or next year, that year is those east of UTC is
used instead. always positive.
Y A full numeric Examples:
representation of a year, 1999 or
4 digits 2003 Format Description Example
y A two digit representation Examples: charact returned values
of a year 99 or 03
er
FULL DATE/TIME
Format Description Example
character returned c ISO 8601 2004-02-
values date 12T15:19:21+00
TIME :00)
a Lowercase Ante am or pm r >> RFC Example: Thu,
meridiem and Post 2822 21 Dec 2000
meridiem
A Uppercase Ante AM or PM formatted 16:01:07 + 0200
meridiem and Post date
meridiem
U Seconds See also time ()
since the - parse any English textual datetime
Unix Epoch description into a Unix timestamp
(January 1, - syntax:
1970, int strtotime ( string $time
00:00:00 [, int $now = time() ] )
GMT)
what is the function name inside of the 6.) Function can have a return value.
code?
A. False
A. 1 B. True
B. value
C. one 7.) Syntax for foreach
D. $t
A. foreach($arr){}
2.) it is required to create a function name B. foreach{}($arr as $value)
for a function C. foreach($value){}
D. foreach($arr as $value){}
A. False
B. True 8.) $g = 200;
function a(){echo “5”;}
3.) Function count($val){ function b(){echo “4”}
$c = 0; ab();
$c += $val;
echo $c; what is the output of the code?
}
count(10); A. 54
count(5); B. 200
C. error
What is the output of the code? D. 45
What is the value of index 0? 10.) Using foreach statement you can
display both the keys and value of each
A. grape element in the array.
B. orange
C. banana A. True
B. False 16.) $t = 100;
function one(){
11.) rsort(), arsort(), and krsort() functions echo “1000”;
are used to sort elements in the array in }
descending order. one();
A. grape
B. orange
34.) Local Variables is one that declared 40.) $num=array(1,2,3,4,5,):
outside a function and is available to all foreach(num as $val){
parts of the program. echo $val
}
A. False – Global Variables
B. True Check the code if valid or invalid?
A. True A. a
B. False B. B
C. $a
38.) var_dump function is same as print_r D. $b
function except it adds additional
information about the data of each 43.) function disp(){
element. function disp2(){
echo “hello”;
A. False }
B. True }
disp();
39.) is a group of PHP statements that disp2();
performs a specific task. Functions are
designed to allow you to reuse the same A. hello
code in different locations. B. blank
C. error
A. Operations D. disp
B. Variables
C. Functions 44.) Array can be used as ordinary array
D. Arrays same as in C and C++ arrays.
A. False
B. True
47.) functions are commonly used for 53.) prints additional information about the
debugging. The point of this of these size and type of the values it discovers
functions is to help you visualize what’s
going on with compound data structures A. var_add()
like arrays. B. var_size()
C. var_info()
A. print_a() and var_size() D. var_dump()
B. print_p() and var_add()
C. print_r() and var_dump() 54.) $a[] = “mango”;
D. print_c() and var_info() $a[] = “apple”;
$a[] = “banana”;
48.) function is used to print the array
structure. Check the code if valid or invalid?
A. print_s A. Valid
B. print_a B. Invalid
C. print_r
D. print_f 55.) Function count($val){
static $c = 0;
49.) is declared inside a function and is $c += $val;
only available within the function in which echo $c;
it is declared. }
Count(4);
A. Global variables Count(3);
B. Dynamic variables
C. Local variables What is the output of the code?
D. Static variables
A. 43
50.) This takes an argument of any type B. Error – count(4) count(3)
and prints it out, which includes printing all C. 47
its parts recursively. D. 7
FORMATIVE 4 A. False
B. True
1.) function is used to print the array
structure 7.) is used to aggregate a series of similar
items together, arranging and
A. print_s dereferencing them in some specific way.
B. print_f
C. print_r A. Variable
B. Index B. val
C. Array C. $value
D. Function D. value$
8.) Function count($val){ 13.) You can insert CSS code inside of a
$c = 0; function.
$c += $val;
echo $c; A. False
} B. True
count(10);
count(5); 14.) Array index in PHP can be also called
as array storage.
What is the output of the code?
A. False – Array keys
A. Error B. True
B. 5
C. 15 15.) Sorts by key
D. 105
A. usort($array)
9.) Function count($val){ B. kusort($array)
static $c = 0; C. ksort($array)
$c += $val; D. krsort($array)
echo $c;
} 16.) used to generate random integers
count(4);
count(3); A. ran()
B. rand()
What is the output of the code? C. random()
D. rndm()
A. 43
B. error 17.) Format character for ISO-8601
C. 47 numeric representation of the day of the
D. 7 week (added in PHP 5.1.0)
A. val$
19.) Format character for a full textual D. array explode (int $delimiter, int $string
representation of the month, such as [, int $limit ] )
January or March
25.) $x = max(10, 5, 3, 20); echo $x;
A. J
B. M What is the output?
C. F
D. T A. 20
B. 5
20.) String number_format( C. 10
float $number, D. 3
int _____;
} 26.) Format character for day of the month
without leading zeros
A. $points
B. $thousands_sep A. j
C. $decimals B. z
D. $dec_points C. m
D. d
21.) Syntax for require once
27.) There will be a warning text if the
A. require_once(filename.php); include file not found.
B. require_once(“filename.inc”);
C. require_once(filename.inc); A. False
D. filename(“require_once”); B. True
22.) In some scripts, a file might be 28.) Syntax to strip white spaces or other
included more than once, causing function characters form the end of a string.
redefinitions, variable reassignments, and
other possible problems. A. string strim(string $str [, string $charlist
])
A. False B. string btrim(string $str [ , string
B. True $charlist])
C. string ctrim(string $str [, string $chalist
23.) Format character for number of days ])
in the given month D. string rtrim(string $str [, string
$charlist ] )
A. m
B. t 29.) Number format can show or hide the
C. d decimal places.
D. n
A. True
24.) Syntax for explode. B. False
A. array explode (string $delimiter, 30.) Format character for a full number
string $string, [, int $limit ] ) representation of a year, 4 digits
B. array explode (int $delimiter, string
$string [, int $limit ] ) A. y
C. array explode (string $delimiter, string B. c
$string [, string $limit ] ) C. Y
D> r
38.) function disp(){
31.) sort() and rsort() does not maintain its function disp2(){
index reference for each values. echo “hello”;
}
A. False }
B. True Disp();
disp2();
32.) You use can functions in different
ways. A. error
B. blank
A. True C. hello
B. False D. disp
33.) Function can only do something 39.) Sorts by value; keeps the same key.
without passing values.
A. rsort($array)
A. True B. asort($array)
B. False C. arsort($array)
D. sort($array)
34.) rsort(), arsort(), krsort() functions are
used to sort elements in the array in 40.) Syntax of a function
descending order.
A. Param_function
A. False B. Function name(param){}
B. True C. Function name {param}
D. Param (function name){}
35.) it is required to create a function
name for a function 41.) function keyword is used in PHP to
declare a function.
A. False
B. True A. True
B. False
36.) The foreach statement is used to
iterate through the element in an array. 42.) specify an array expression within a
set of parenthesis following the foreach
A. True keyword.
B. False
A. False
37.) PHP has a built-in function to perform B. True
operations.
43.) $g = 200;
A. True function a(){echo “5”;}
B. False function b(){echo “4”;}
a();
A. 4
B. 5
C. 200
D. Error
50.) used to declare constants
44.) $x = floor(5.2); echo $x;
A. function
What is the output? B. define
C. derive
A. Blank D. set
B. 6
C. Error 51.) Format character for a short textual
D. 5 representation of a month, three letters
A. Titles
B. Footer
C. Body
D. Content