0% found this document useful (0 votes)
34 views

Web Development BCS IV Sem Unit II

Php

Uploaded by

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

Web Development BCS IV Sem Unit II

Php

Uploaded by

cocsit21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

What is PHP?

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP is free to download and use
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF files. You can
also output any text, such as XHTML and XML.

Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7

 PHP 7 is much faster than the previous popular stable release (PHP 5.6)
 PHP 7 has improved Error Handling
 PHP 7 supports stricter Type Declarations for function arguments
 PHP 7 supports new operators (like the spaceship operator: <=>)

Basic PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:


<?php

// PHP code goes here

?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

Example
A simple .php file with both HTML code and PHP code:

<!DOCTYPE html>

<html>

<body>

<h1>My first PHP page</h1>

<?php

echo "Hello World!";

?>

</body>

</html>

Note: PHP statements end with a semicolon (;).

PHP Case Sensitivity


In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive.

In the example below, all three echo statements below are equal and legal:

Example
ECHO is the same as echo:

<!DOCTYPE html>

<html>

<body>
<?php

ECHO "Hello World!<br>";

echo "Hello World!<br>";

EcHo "Hello World!<br>";

?>

</body>

</html>

Note: However; all variable names are case-sensitive!

Look at the example below; only the first statement will display the value of the $color variable!
This is because $color, $COLOR, and $coLOR are treated as three different variables:

Example
$COLOR is not same as $color:

<html>

<body>

<?php
$color = "red";

echo "My car is " . $color . "<br>";

echo "My house is " . $COLOR . "<br>";

echo "My boat is " . $coLOR . "<br>";

?>

</body>

</html>

Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code
 Leave out some parts of your code
PHP supports several ways of commenting:

Example
Syntax for comments in PHP code:

// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

Single Line Comments


Single line comments start with //.

Any text between // and the end of the line will be ignored (will not be executed).

You can also use # for single line comments, but in this tutorial we will use //.

The following examples uses a single-line comment as an explanation:

Example
A comment before the code:

// Outputs a welcome message:

echo "Welcome Home!";

Example

A comment at the end of a line:

echo "Welcome Home!"; // Outputs a welcome message

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

Example
Multi-line comment as an explanation:
/*

The next statement will

print a welcome message

*/

echo "Welcome Home!";

PHP Variables
Variables are "containers" for storing information.

Creating (Declaring) PHP Variables


In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example
<html>

<body>

<?php

$x = 5;

$y = "John";

echo $x;

echo "<br>";

echo $y;

?>

</body>

</html>

o/p

5
John

In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".
Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.

Think of variables as containers for storing data.

PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!

Output Variables
The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example
<html>

<body>

<?php

$txt = "W3Schools.com";

echo "I love $txt!";

?>

</body>

</html>

o/p

I love W3Schools.com!
The following example will produce the same output as the example above:

Example
<html>

<body>

<?php

$txt = "W3Schools.com";

echo "I love " . $txt . "!";

?>

</body>

</html>

The following example will output the sum of two variables:

Example
<html>

<body>

<?php

$x = 5;

$y = 4;

echo $x + $y;

?>

</body>

</html>

Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the
variable.

Example
<html>
<body>

$x = 5; // $x is an integer

$y = "John"; // $y is a string

<?php

$x = 5; // $x is an integer

$y = "John"; // $y is a string

echo $x;

echo $y;

?>

</body>

</html>

o/p

5John

PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

Get the Type


To get the data type of a variable, use the var_dump() function.

Example
The var_dump() function returns the data type and the value:

<html>

<body>

<?php

$x = 5;
var_dump($x);

?>

</body>

</html>

Output-

int(5)

PHP Functions
The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.

PHP Built-in Functions


PHP has over 1000 built-in functions that can be called directly, from within a script, to perform
a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP Reference
The PHP reference contains different categories of all PHP functions, keywords and constants,
along with examples.

Array, Calendar, Date, Directory, Error, Exception, Filesystem, Filter, FTP, JSON,
Keywords, Libxml, Mail, Math, Misc, MySQLi, Network, Output, RegEx, Simple
XML, Stream, String, Var, Handling, XML, Parser, Zip, Timezones.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

 A function is a block of statements that can be used repeatedly in a program.


 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

Create a Function
A user-defined function declaration starts with the keyword function, followed by the name of the
function:
Example

function myMessage() {

echo "Hello world!";

Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.

Tip: Give the function a name that reflects what the function does!

Call a Function

To call the function, just write its name followed by parentheses ():

Example
<html>

<body>

<?php

function myMessage() {

echo "Hello world!";

myMessage();

?>

</body>

</html>

o/p

Hello world!

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When
the familyName() function is called, we also pass along a name, e.g. ("Jani"), and the name is
used inside the function, which outputs several different first names, but an equal last name:

<html>

<body>

<?php

function familyName($fname, $year) {

echo "$fname Refsnes. Born in $year <br>";

familyName("Hege","1975");

familyName("Stale","1978");

familyName("Kai Jim","1983");

?>

</body>

</html>

o/p

Hege Refsnes. Born in 1975


Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983

PHP Functions - Returning values


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

Example
<html>

<body>

<?php

function sum($x, $y) {

$z = $x + $y;

return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";

echo "7 + 13 = " . sum(7,13) . "<br>";

echo "2 + 4 = " . sum(2,4);

?>

</body>

</html>

o/p

5 + 10 = 15
7 + 13 = 20
2+4=6

Passing Arguments by Reference


In PHP, arguments are usually passed by value, which means that a copy of the value is used in
the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the
variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example
<html>

<body>

<?php

function add_five(&$value) {

$value += 5;

$num = 2;

add_five($num);

echo $num;

?>

</body>
</html>

o/p

PHP Array
An array is a special variable that can hold many values under a single name, and you can access
the values by referring to an index number or name.

PHP Array Types


In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

Array Items
Array items can be of any data type.

The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.

You can have different data types in the same array.

<!DOCTYPE html>

<html>

<body>

<?php

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

echo count($cars)."<br>";

echo $cars[0];

?>

</body>

</html>
Output:

3
Volvo

PHP Indexed Arrays


In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.

<!DOCTYPE html>

<html>

<body>

<pre>

<?php

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

var_dump($cars);

?>

</pre>

</body>

</html>

Output:

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

Access Indexed Arrays


To access an array item you can refer to the index number.
Example

Display the first array item:

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

echo $cars[0];

Change Value
To change the value of an array item, use the index number:

Example

Change the value of the second item:

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

$cars[1] = "Ford";

var_dump($cars);

Index Number
The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but
there are exceptions.

New items get the next index number, meaning one higher than the highest existing index.

So if you have an array like this:

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";

And if you use the array_push() function to add a new item, the new item will get the index 3:

Example
<!DOCTYPE html>

<html>

<body>

<pre>

<?php

$cars[0] = "Volvo";
$cars[1] = "BMW";

$cars[2] = "Toyota";

array_push($cars, "Ford");

var_dump($cars);

?>

</pre>

</body>

</html>

Output:
array(4) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
[3]=>
string(4) "Ford"
}

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

<!DOCTYPE html>

<html>

<body>

<pre>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

?>

</pre>

</body>

</html>
Output:

array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}

Access Associative Arrays


To access an array item you can refer to the key name.

<!DOCTYPE html>

<html>

<body>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

echo $car["model"];

?>

</body>

</html>

Output:

Mustang

Change Value
To change the value of an array item, use the key name:

Example
<!DOCTYPE html>

<html>
<body>

<pre>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

$car["year"] = 2024;

var_dump($car);

?>

</pre>

</body>

</html>

Output:

array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}

Array Keys
When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1
for each item, so the array above could also be created with keys:

<!DOCTYPE html>

<html>

<body>

<pre>

<?php

$cars = [

0 => "Volvo",
1 => "BMW",

2 =>"Toyota"

];

var_dump($cars);

?>

</pre>

</body>

</html>

Output:

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Declare

Empty Array
You can declare an empty array first, and add items to it later:

<!DOCTYPE html>

<html>

<body>

<pre>

<?php

$cars = [];

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";
var_dump($cars);

?>

</pre>

</body>

</html>

Output:

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of
arrays).

First, take a look at the following table:

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:

$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.

To get access to the elements of the $cars array we must point to the two indices (row and
column):

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

?>

</body>
</html>

Output:

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

PHP Array related Functions


Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input array

array_combine() Creates an array by using the elements from one "keys" array and one
"values" array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values only)

array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)

array_diff_key() Compare arrays, and returns the differences (compare keys only)

array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values,
using a user-defined key comparison function)

array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a
user-defined key comparison function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only)

array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values,
using a user-defined key comparison function)

array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a
user-defined key comparison function)

array_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array

array_map() Sends each value of an array to a user-made function, which returns new
values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified value, to an array

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array

array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined function

array_replace() Replaces the values of the first array with the values from following
arrays

array_replace_recursive() Replaces the values of the first array with the values from following
arrays recursively

array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the key

array_shift() Removes the first element from an array, and returns the value of the
removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array


array_udiff() Compare arrays, and returns the differences (compare values only, using
a user-defined key comparison function)

array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values,
using a built-in function to compare the keys and a user-defined function
to compare the values)

array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values,
using two user-defined key comparison functions)

array_uintersect() Compare arrays, and returns the matches (compare values only, using a
user-defined key comparison function)

array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values,
using a built-in function to compare the keys and a user-defined function
to compare the values)

array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values,
using two user-defined key comparison functions)

array_unique() Removes duplicate values from an array

array_unshift() Adds one or more elements to the beginning of an array

array_values() Returns all the values of an array

array_walk() Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an array

arsort() Sorts an associative array in descending order, according to the value

asort() Sorts an associative array in ascending order, according to the value

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

each() Deprecated from PHP 7.2. Returns the current key and value pair from
an array

end() Sets the internal pointer of an array to its last element

extract() Imports variables into the current symbol table from an array

in_array() Checks if a specified value exists in an array

key() Fetches a key from an array


krsort() Sorts an associative array in descending order, according to the key

ksort() Sorts an associative array in ascending order, according to the key

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order" algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements

reset() Sets the internal pointer of an array to its first element

rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined comparison function and


maintains the index association

uksort() Sorts an array by keys using a user-defined comparison function

usort() Sorts an array by values using a user-defined comparison function

Class and Objects in php

Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>

Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_name() and get_name() for setting and getting the $name property:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

Note: In a class, variables are called properties and functions are called methods!

Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has
all the properties and methods defined in the class, but they will have different property values.

Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

Example
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

Output:
Apple
Banan

PHP Object Inheritance

Inheritance is an important principle of object oriented programming methodology. Using this


principle, relation between two classes can be defined. PHP supports inheritance in its object
model.
PHP uses extends keyword to establish relationship between two classes.
Syntax
class B extends A

where A is the base class (also called parent called) and B is called a subclass or child class.
Child class inherits public and protected methods of parent class. Child class may redefine or
override any of inherited methods. If not, inherited methods will retain their functionality as
defined in parent class, when used with object of child class.

Definition of parent class must precede child class definition. In this case, definition of A class
should appear before definition of class B in the script.

Example
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?>
If autoloading is enabled, definition of parent class is obtained by loading the class script.

Inheritance Example

Following code shows that child class inherits public and protected members of parent class

Example

<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class
";
}
protected function protectedmethod(){
echo "This is protected method of parent class
";
}
private function privatemethod(){
echo "This is private method of parent class
";
}
}
class childclass extends parentclass{
public function childmethod(){
$this->protectedmethod();
//$this->privatemethod(); //this will produce error
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>

Output

This will produce following result. −

This is public method of parent class


This is protected method of parent class
PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from
context 'childclass'
PHP Strings
A string is a sequence of characters, like "Hello world!".

Strings in PHP are surrounded by either double quotation marks, or single quotation marks.

<html>

<body>

<?php

echo "Hello";

print "Hello";

?>

</body>
</html>

Output
HelloHello

Double or Single Quotes?


You can use double or single quotes, but you should be aware of the differences between the
two.

Double quoted strings perform action on special characters.

E.g. when there is a variable in the string, it returns the value of the variable:

Example
Double quoted string literals perform operations for special characters:

<html>

<body>

<?php

$x = "John";

echo "Hello $x";


?>

</body>
</html>

Output
Hello John

Other PHP String related Functions


The PHP string functions are part of the PHP core. No installation is required to use these
functions.

Function Description

addcslashes() Returns a string with backslashes in front of the specified characters

addslashes() Returns a string with backslashes in front of predefined characters

bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes whitespace or other characters from the right end of a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

crc32() Calculates a 32-bit CRC for a string

crypt() One-way string hashing

echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

get_html_translation_table() Returns the translation table used by htmlspecialchars() and


htmlentities()

hebrev() Converts Hebrew text to visual text


hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>

hex2bin() Converts a string of hexadecimal values to ASCII characters

html_entity_decode() Converts HTML entities to characters

htmlentities() Converts characters to HTML entities

htmlspecialchars_decode() Converts some predefined HTML entities to characters

htmlspecialchars() Converts some predefined characters to HTML entities

implode() Returns a string from the elements of an array

join() Alias of implode()

lcfirst() Converts the first character of a string to lowercase

levenshtein() Returns the Levenshtein distance between two strings

localeconv() Returns locale numeric and monetary formatting information

ltrim() Removes whitespace or other characters from the left side of a string

md5() Calculates the MD5 hash of a string

md5_file() Calculates the MD5 hash of a file

metaphone() Calculates the metaphone key of a string

money_format() Returns a string formatted as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks in front of each newline in a string

number_format() Formats a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

parse_str() Parses a query string into variables

print() Outputs one or more strings

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to an 8-bit string

quoted_printable_encode() Converts an 8-bit string to a quoted printable string

quotemeta() Quotes meta characters


rtrim() Removes whitespace or other characters from the right side of a string

setlocale() Sets locale information

sha1() Calculates the SHA-1 hash of a string

sha1_file() Calculates the SHA-1 hash of a file

similar_text() Calculates the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Writes a formatted string to a variable

sscanf() Parses input from a string according to a format

str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces some characters in a string (case-insensitive)

str_pad() Pads a string to a new length

str_repeat() Repeats a string a specified number of times

str_replace() Replaces some characters in a string (case-sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Count the number of words in a string

strcasecmp() Compares two strings (case-insensitive)

strchr() Finds the first occurrence of a string inside another string (alias of
strstr())

strcmp() Compares two strings (case-sensitive)

strcoll() Compares two strings (locale based string comparison)

strcspn() Returns the number of characters found in a string before any part of
some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes()

stripslashes() Unquotes a string quoted with addslashes()


stripos() Returns the position of the first occurrence of a string inside another
string (case-insensitive)

stristr() Finds the first occurrence of a string inside another string (case-
insensitive)

strlen() Returns the length of a string

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-


insensitive)

strnatcmp() Compares two strings using a "natural order" algorithm (case-


sensitive)

strncasecmp() String comparison of the first n characters (case-insensitive)

strncmp() String comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

strpos() Returns the position of the first occurrence of a string inside another
string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

strripos() Finds the position of the last occurrence of a string inside another
string (case-insensitive)

strrpos() Finds the position of the last occurrence of a string inside another
string (case-sensitive)

strspn() Returns the number of characters found in a string that contains only
characters from a specified charlist

strstr() Finds the first occurrence of a string inside another string (case-
sensitive)

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

substr_compare() Compares two strings from a specified start position (binary safe and
optionally case-sensitive)

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

trim() Removes whitespace or other characters from both sides of a string

ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Wraps a string to a given number of characters

PHP Date and Time


The PHP date() function is used to format a date and/or a time.

The PHP Date() Function


The PHP date() function formats a timestamp to a more readable date and time.

Syntax
date(format,timestamp)

Parameter Description

format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp. Default is the current date and time

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.

Get a Date
The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

 d - Represents the day of the month (01 to 31)


 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
 l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.

The example below formats today's date in three different ways:

<html>

<body>

<?php

echo "Today is " . date("Y/m/d") . "<br>";

echo "Today is " . date("Y.m.d") . "<br>";

echo "Today is " . date("Y-m-d") . "<br>";

echo "Today is " . date("l");

?>

</body>
</html>

Output:
Today is 2020/11/03
Today is 2020.11.03
Today is 2020-11-03
Today is Tuesday

Get a Time
Here are some characters that are commonly used for times:

 H - 24-hour format of an hour (00 to 23)


 h - 12-hour format of an hour with leading zeros (01 to 12)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds with leading zeros (00 to 59)
 a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

<html>

<body>

<?php
echo "The time is " . date("h:i:sa");

?>

</body>
</html>

Output:
The time is 10:29:46am

PHP Date/Time Functions


The date/time functions allow you to get the date and time from the server where your PHP
script runs. You can then use the date/time functions to format the date and time in several ways.

Note: These functions depend on the locale settings of your server. Remember to take daylight
saving time and leap years into consideration when working with these functions.

PHP Date/Time Functions


Function Description

checkdate() Validates a Gregorian date

date_add() Adds days, months, years, hours, minutes, and seconds to a


date

date_create_from_format() Returns a new DateTime object formatted according to a


specified format

date_create() Returns a new DateTime object

date_date_set() Sets a new date

date_default_timezone_get() Returns the default timezone used by all date/time functions

date_default_timezone_set() Sets the default timezone used by all date/time functions

date_diff() Returns the difference between two dates

date_format() Returns a date formatted according to a specified format

date_get_last_errors() Returns the warnings/errors found in a date string

date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string

date_interval_format() Formats the interval


date_isodate_set() Sets the ISO date

date_modify() Modifies the timestamp

date_offset_get() Returns the timezone offset

date_parse_from_format() Returns an associative array with detailed info about a


specified date, according to a specified format

date_parse() Returns an associative array with detailed info about a


specified date

date_sub() Subtracts days, months, years, hours, minutes, and seconds


from a date

date_sun_info() Returns an array containing info about sunset/sunrise and


twilight begin/end, for a specified day and location

date_sunrise() Returns the sunrise time for a specified day and location

date_sunset() Returns the sunset time for a specified day and location

date_time_set() Sets the time

date_timestamp_get() Returns the Unix timestamp

date_timestamp_set() Sets the date and time based on a Unix timestamp

date_timezone_get() Returns the time zone of the given DateTime object

date_timezone_set() Sets the time zone for the DateTime object

date() Formats a local date and time

getdate() Returns date/time information of a timestamp or the current


local date/time

gettimeofday() Returns the current time

gmdate() Formats a GMT/UTC date and time

gmmktime() Returns the Unix timestamp for a GMT date

gmstrftime() Formats a GMT/UTC date and time according to locale


settings

idate() Formats a local time/date as integer

localtime() Returns the local time


microtime() Returns the current Unix timestamp with microseconds

mktime() Returns the Unix timestamp for a date

strftime() Formats a local time and/or date according to locale settings

strptime() Parses a time/date generated with strftime()

strtotime() Parses an English textual datetime into a Unix timestamp

time() Returns the current time as a Unix timestamp

timezone_abbreviations_list() Returns an associative array containing dst, offset, and the


timezone name

timezone_identifiers_list() Returns an indexed array with all timezone identifiers

timezone_location_get() Returns location information for a specified timezone

timezone_name_from_ abbr() Returns the timezone name from abbreviation

timezone_name_get() Returns the name of the timezone

timezone_offset_get() Returns the timezone offset from GMT

timezone_open() Creates new DateTimeZone object

timezone_transitions_get() Returns all transitions for the timezone

timezone_version_get() Returns the version of the timezonedb

You might also like