Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional...

32
Additional Functions of PHP by Rocky Sir Company URL: http://suvenconsultants.com Page 1 DATE AND TIME Function time() Description PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer. The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp. Syntax time() Example <?php print time(); ?> Output 948316201 Function getdate() Description The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time(). Following table lists the elements contained in the array returned by getdate(). Key Description Example seconds Seconds past the minutes (0-59) 20 minutes Minutes past the hour (0 - 59) 29 hours Hours of the day (0 - 23) 22 mday Day of the month (1 - 31) 11 wday Day of the week (0 - 6) 4 mon Month of the year (1 - 12) 7

Transcript of Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional...

Page 1: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 1

DATE AND TIME

Function time()

Description PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer. The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

Syntax time()

Example <?php print time(); ?>

Output 948316201

Function getdate()

Description The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

Following table lists the elements contained in the array returned by getdate().

Key Description Example

seconds Seconds past the minutes (0-59) 20

minutes Minutes past the hour (0 - 59) 29

hours Hours of the day (0 - 23) 22

mday Day of the month (1 - 31) 11

wday Day of the week (0 - 6) 4

mon Month of the year (1 - 12) 7

Page 2: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 2

year Year (4 digits) 1997

yday Day of year ( 0 - 365 ) 19

weekday Day of the week Thursday

month Month of the year January

0 Timestamp 948370048

Syntax getdate()

Example <?php $date_array = getdate(); foreach ( $date_array as $key => $val ) { print "$key = $val<br />"; } $formated_date = "Today's date: "; $formated_date .= $date_array[mday] . "/"; $formated_date .= $date_array[mon] . "/"; $formated_date .= $date_array[year]; print $formated_date; ?>

Output seconds = 27 minutes = 25 hours = 11 mday = 12 wday = 6 mon = 5 year = 2007 yday = 131 weekday = Saturday month = May 0 = 1178994327 Today's date: 12/5/2007

Function date()

Description The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

The date() optionally accepts a time stamp if ommited then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.

Following table lists the codes that a format string can contain:

Page 3: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 3

Format Description Example

a 'am' or 'pm' lowercase pm

A 'AM' or 'PM' uppercase PM

d Day of month, a number with leading zeroes 20

D Day of week (three letters) Thu

F Month name January

h Hour (12-hour format - leading zeroes) 12

H Hour (24-hour format - leading zeroes) 22

g Hour (12-hour format - no leading zeroes) 12

G Hour (24-hour format - no leading zeroes) 22

i Minutes ( 0 - 59 ) 23

j Day of the month (no leading zeroes 20

l (Lower 'L') Day of the week Thursday

L Leap year ('1' for yes, '0' for no) 1

m Month of year (number - leading zeroes) 1

M Month of year (three letters) Jan

r The RFC 2822 formatted date Thu, 21 Dec 2000 16:01:07 +0200

n Month of year (number - no leading zeroes) 2

s Seconds of hour 20

U Time stamp 948372444

y Year (two digits) 06

Y Year (four digits) 2006

z Day of year (0 - 365) 206

Z Offset in seconds from GMT +5

Syntax date(format,timestamp)

Example <?php print date("m/d/y G.i:s<br>", time()); print "Today is "; print date("j of F Y, \a\\t g.i a", time()); ?>

Output 02/05/15 10.27:22Today is 5 2015f February 2015, at 10.27 am

Function Date_create()

Page 4: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 4

Description The date_create() function returns a new DateTime object.

Syntax $date=date_create("2013-03-15");

Example <?php

$date=date_create("2013-03-15");

echo date_format($date,"Y/m/d");

?>

Output 2013/03/15

Function

date_parse()

Description Returns associative array with detailed info about given date

Syntax array date_parse ( string $date )

Example <?php

print_r(date_parse("2006-12-12 10:00:00.5"));

?>

Output Array ( [year] => 2006 [month] => 12 [day]

=> 12 [hour] => 10 [minute] => 0 [second] =>

0 [fraction] => 0.5 [warning_count] => 0

[warnings] => Array ( ) [error_count] => 0

[errors] => Array ( ) [is_localtime] => )

Function

date_modify

Description date_modify — Alters the timestamp

Syntax public DateTime DateTime::modify ( string $modify )

Example <?php

$date = new DateTime('2006-12-12');

$date->modify('+1 day');

echo $date->format('Y-m-d');

?>

Output 2006-12-13

Function

getdate()

Page 5: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 5

Description Get date/time information

Syntax array getdate ([ int $timestamp = time() ] )

Example <?php

$today = getdate();

print_r($today);

?>

Output Array ( [seconds] => 37 [minutes] => 25

[hours] => 11 [mday] => 2 [wday] => 1 [mon]

=> 2 [year] => 2015 [yday] => 32 [weekday]

=> Monday [month] => February [0] =>

1422872737 )

Function

microtime()

Description The microtime() function returns the current Unix timestamp with microseconds.

Syntax microtime(get_as_float);

Example <?php echo(microtime()); ?>

Output 0.71496300 1422875681

Function

Idate()

Description Format a local time/date as integer

Syntax int idate ( string $format [, int $timestamp = time() ] )

Example <?php

$timestamp = strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format

// however, as this would start with a "0", it

// only prints "4"

echo idate('y', $timestamp);

?>

Output 4

Page 6: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 6

COOKIES

Function setcookie()

Description PHP provided setcookie() function to set a cookie. This function

requires upto six arguments and should be called before <html> tag.

For each cookie this function has to be called separately.

Syntax setcookie(name, value, expire, path, domain, secure, httponly);

Example <?php setcookie("TestCookie", 'something from somewhere', time()+3600, "/", "example.com", 1); print_r($_COOKIE); echo $_COOKIE["TestCookie"]; ?> name=TestCookie value= 'something from somewhere' expire= time()+3600 path= "/" domain= "example.com" httponly=1 name The name of the cookie. value The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename'] expire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). Note: You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT,

Page 7: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 7

this is because PHP does this conversion internally. path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. The default value is the current directory that the cookie is being set in. domain The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading .to match all subdomains. secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection. httponly When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

Function isset()

Description You can use isset() function to check if a cookie is set or not.

Syntax isset($_COOKIE["name"])

Example <html> <head> <title>Accessing Cookies with PHP</title> </head> <body> <?php if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />"; else echo "Sorry... Not recognized" . "<br />"; ?>

Page 8: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 8

</body> </html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired:

<?php

setcookie( "name", "", time()- 60, "/","", 0);

setcookie( "age", "", time()- 60, "/","", 0);

?>

<html>

<head>

<title>Deleting Cookies with PHP</title>

</head>

<body>

<?php echo "Deleted Cookies" ?>

</body>

</html>

ERROR HANDLING

Function

debug_backtrace()

Description debug_backtrace() generates a PHP backtrace.

Syntax array debug_backtrace ([ int $options =

DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )

Example

<?php

function a_test($str)

{

echo "\nHi: $str";

var_dump(debug_backtrace());

}

a_test('friend');

?>

Page 9: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 9

output

Hi: friendarray(1) { [0]=> array(4) { ["file"]=> string(34)

"C:\xampp\htdocs\phpfunctions\debugbacktrace

.php" ["line"]=>int(9) ["function"]=>

string(6) "a_test" ["args"]=> array(1) {

[0]=>&string(6) "friend" } } }

Function debug_print_backtrace()

Description debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Syntax void debug_print_backtrace ([ int $options =

0 [, int $limit = 0 ]] )

Example <?php

// include.php file

function a() {

b();

}

function b() {

c();

}

function c(){

debug_print_backtrace();

}

a();

?>

<?php

// test.php file

include 'include.php';

?>

output #0 c() called at

[C:\xampp\htdocs\phpfunctions\include.php:9] #1

b() called at

[C:\xampp\htdocs\phpfunctions\include.php:5] #2

a() called at

[C:\xampp\htdocs\phpfunctions\include.php:16] #3

include(C:\xampp\htdocs\phpfunctions\include.php)

Page 10: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 10

called at

[C:\xampp\htdocs\phpfunctions\test.php:5]

Function

trigger_error()

Description The trigger_error() function creates a user-level error

message.

The trigger_error() function can be used with the built-in

error handler, or with a user-defined function set by

theset_error_handler() function.

Syntax trigger_error(errormsg,errortype);

Example <?php

$usernum=11;

if ($usernum>10)

{

trigger_error("Number cannot be larger than

10",E_USER_ERROR);

}

?>

Output

Fatal error: Number cannot be larger than 10

in C:\xampp\htdocs\phpfunctions\a.php on

line 5

Function

user_error()

Description The user_error() function creates a user-level error message.

The user_error() function can be used with the built-in error

handler, or with a user-defined function set by

theset_error_handler() function.

Page 11: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 11

Syntax user_error(errormsg,errortype);

Example <?php

$usernum=11;

if ($usernum>10)

{

user_error("Number cannot be larger than 10",E_USER_ERROR);

}

?>

Output

Fatal error: Number cannot be larger than 10

in C:\xampp\htdocs\phpfunctions\a.php on

line 5

Function

set_error_handler()

Description The set_error_handler() function sets a user-defined error

handler function.

Syntax set_error_handler(errorhandler,E_ALL|E_STRICT);

errorhandler- Required. Specifies the name of the function to

be run at errors

E_ALL|E_STRICT- Optional. Specifies on which error report level

the user-defined error will be shown. Default is "E_ALL"

Example <?php

// A user-defined error handler function

function myErrorHandler($errno, $errstr, $errfile, $errline) {

echo "<b>Custom error:</b> [$errno] $errstr<br>";

echo " Error on line $errline in $errfile<br>";

}

// Set user-defined error handler function

set_error_handler("myErrorHandler");

$test=2;

// Trigger error

if ($test>1) {

trigger_error("A custom error has been triggered");

}

?>

Output Custom error: [1024] A custom error has been

triggered

Page 12: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 12

Error on line 15 in

C:\xampp\htdocs\phpfunctions\err.php

Function

set_exception_handler()

Description The set_exception_handler() function sets a user-defined

exception handler function.

The script will stop executing after the exception handler is

called.

Syntax set_exception_handler(exceptionhandler);

Example <?php

// A user-defined exception handler function

function myException($exception) {

echo "<b>Exception:</b> ", $exception->getMessage();

}

// Set user-defined exception handler function

set_exception_handler("myException");

// Throw exception

throw new Exception("Uncaught exception occurred!");

?>

Output Exception: Uncaught exception occurred!

Page 13: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 13

Function

restore_error_handler()

Description The restore_error_handler() function restores the previous

error handler.

This function is used to restore the previous error handler after

changing it with the set_error_handler() function.

Syntax restore_error_handler();

Example <?php

// A user-defined error handler function

function myErrorHandler($errno, $errstr, $errfile, $errline) {

echo "<b>Custom error:</b> [$errno] $errstr<br>";

echo " Error on line $errline in $errfile<br>";

}

// Set user-defined error handler function

set_error_handler("myErrorHandler");

$test=2;

// Trigger error

if ($test>1) {

trigger_error("A custom error has been triggered");

}

// Restore previous error handler

restore_error_handler();

// Trigger error again

if ($test>1) {

trigger_error("A custom error has been triggered");

}

?>

Output Custom error: [1024] A custom error has been

triggered

Error on line 15 in

C:\xampp\htdocs\phpfunctions\restore.php

Notice: A custom error has been triggered

in C:\xampp\htdocs\phpfunctions\restore.php on

line 23

Page 14: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 14

Function

restore_exception_handler()

Description The restore_exception_handler() function restores the

previous exception handler.

This function is used to restore the previous exception handler

after changing it with the set_exception_handler()function.

Syntax restore_exception_handler();

Example <?php

// Two user-defined exception handler functions

function myException1($exception) {

echo "[" . __FUNCTION__ . "]" . $exception->getMessage();

}

function myException2($exception) {

echo "[" . __FUNCTION__ . "]" . $exception->getMessage();

}

set_exception_handler("myException1");

set_exception_handler("myException2");

restore_exception_handler();

// Throw exception

throw new Exception("This triggers the first exception

handler...");

?>

Output [myException1]This triggers the first

exception handler...

Page 15: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 15

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Value Constant Description

1 E_ERROR Fatal run-time errors. Execution of the script is halted

2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted

4 E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser.

8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally

16 E_CORE_ERROR Fatal errors that occur during PHP's initial startup.

32 E_CORE_WARNING Non-fatal run-time errors. This occurs during PHP's initial startup.

256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()

512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()

1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()

2048 E_STRICT Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())

8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

EXCEPTION HANDLING

Function Try, Throw, Catch

Description Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".

Catch - - A "catch" block retrieves an exception and creates an object containing the exception information.

Syntax Try {--------} Catch (Exception $e) { ----------------- }

Example <?php try { $error = 'Always throw this error';

Page 16: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 16

throw new Exception($error); // Code following an exception is not executed. echo 'Never executed'; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Continue execution echo 'Hello World'; ?>

In the above example $e->getMessage function is uded to get error message. There are following functions which can be used from Exception class.

getMessage()- message of exception getCode() - code of exception getFile() - source filename getLine() - source line getTrace() - n array of the backtrace() getTraceAsString() - formated string of trace

Function set_exception_handler()

Description Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Syntax string set_exception_handler ( callback $exception_handler )

Example <?php function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n"; ?>

Page 17: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 17

SORTING

Function sort()

Description sort arrays in ascending order

Syntax Sort(array);

Example <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); ?>

Output BMW Toyota Volvo

Function rsort()

Description sort arrays in descending order

Syntax rsort(array);

Example <?php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars); ?>

Output Volvo Toyota BMW

Function asort()

Description sort associative arrays in ascending order, according to the value

Syntax asort(array);

Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); asort($age); ?>

Output Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43

Function ksort()

Page 18: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 18

Description sort associative arrays in ascending order, according to the key

Syntax ksort(array);

Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); ksort($age); ?>

Output Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35

Function arsort()

Description sort associative arrays in descending order, according to the value

Syntax arsort(array);

Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); arsort($age); ?>

Output Key=Joe, Value=43 Key=Ben, Value=37 Key=Peter, Value=35

Function krsort()

Description sort associative arrays in descending order, according to the key

Syntax krsort(array);

Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); krsort($age); ?>

Output Key=Peter, Value=35 Key=Joe, Value=43 Key=Ben, Value=37

Page 19: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 19

SESSION

session_abort — Discard session array changes and finish session

session_cache_expire — Return current cache expire

session_cache_limiter — Get and/or set the current cache limiter

session_commit — Alias of session_write_close

session_decode — Decodes session data from a session encoded string

session_destroy — Destroys all data registered to a session

session_encode — Encodes the current session data as a session encoded string

session_get_cookie_params — Get the session cookie parameters

session_id — Get and/or set the current session id

session_is_registered — Find out whether a global variable is registered in a session

session_module_name — Get and/or set the current session module

session_name — Get and/or set the current session name

session_regenerate_id — Update the current session id with a newly generated one

session_register_shutdown — Session shutdown function

session_register — Register one or more global variables with the current session

session_reset — Re-initialize session array with original values

session_save_path — Get and/or set the current session save path

session_set_cookie_params — Set the session cookie parameters

session_set_save_handler — Sets user-level session storage functions

session_start — Start new or resume existing session

session_status — Returns the current session status

session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables

session_write_close — Write session data and end session

Page 20: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 20

ARRAY

Function array_key_exists()

Description The array_key_exists() function checks an array for a

specified key, and returns true if the key exists and false if the key does not exist.

Syntax array_key_exists(key,array)

Example <?php $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (array_key_exists("Volvo",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?>

Output Key exists!

Function array_keys ()

Description The array_keys() function returns an array containing the keys.

Syntax array_keys(array,value,strict)

Example <?php

$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");

print_r(array_keys($a));

?>

Output Array ( [0] => Volvo [1] => BMW [2] => Toyota )

Function array_map();

Description The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-

made function.

Syntax array_map(myfunction,array1,array2,array3...)

Example <?php

function myfunction($num)

Page 21: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 21

{

return($num*$num);

}

$a=array(1,2,3,4,5);

print_r(array_map("myfunction",$a));

?>

Output Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

Function array_merge_recursive()

Description The array_merge_recursive() function merges one ore more arrays

into one array.

The difference between this function and the array_merge() function is

when two or more array elements have the same key. Instead of

override the keys, the array_merge_recursive() function makes the

value as an array.

Syntax array_merge_recursive(array1,array2,array3...)

Example <?php

$a1=array("a"=>"red","b"=>"green");

$a2=array("c"=>"blue","b"=>"yellow");

print_r(array_merge_recursive($a1,$a2));

?>

Output Array ( [a] => red [b] => Array ( [0] => green [1] => yellow ) [c] => blue )

Function array_merge()

Description The array_merge() function merges one or more arrays into one array.

Tip: You can assign one array to the function, or as many as you like.

Syntax array_merge(array1,array2,array3...)

Example <?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2));

Page 22: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 22

?>

Output Array ( [0] => red [1] => green [2] => blue [3] => yellow )

Function array_multisort()

Description The array_multisort() function returns a sorted array. You can assign

one or more arrays. The function sorts the first array, and the other

arrays follow, then, if two or more values are the same, it sorts the

next array, and so on.

Note: String keys will be maintained, but numeric keys will be re-

indexed, starting at 0 and increase by 1.

Syntax array_multisort(array1,sorting order,sorting type,array2,array3...)

Example <?php

$a=array("Dog","Cat","Horse","Bear","Zebra");

array_multisort($a);

print_r($a);

?>

Output Array ( [0] => Bear [1] => Cat [2] => Dog [3] => Horse [4] => Zebra )

Function array_pad()

Description Pad array to the specified length with a value

Syntax array_pad(array,size,value)

Example <?php $a=array("red","green"); print_r(array_pad($a,5,"blue")); ?>

Output Array ( [0] => red [1] => green [2] => blue [3] => blue [4] => blue )

Function array_rand()

Page 23: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 23

Description thearray_rand() function returns a random key from an array, or it

returns an array of random keys if you specify that the function should

return more than one key.

Syntax array_rand(array,number)

Example <?php $a=array("red","green","blue","yellow","brown"); $random_keys=array_rand($a,3); echo $a[$random_keys[0]]."<br>"; echo $a[$random_keys[1]]."<br>"; echo $a[$random_keys[2]]; ?>

Output red

green

yellow

Function array_reduce()

Description The array_reduce() function sends the values in an array to a user-

defined function, and returns a string.

Note: If the array is empty and initial is not passed, this function

returns NULL.

Syntax array_reduce(array,myfunction,initial)

Example <?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction")); ?>

Output -Dog-Cat-Horse

Function array_replace_recursive()

Page 24: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 24

Description The array_replace_recursive() function replaces the values of the first

array with the values from following arrays recursively.

Tip: You can assign one array to the function, or as many as you like.

Syntax array_replace_recursive(array1,array2,array3...)

Example <?php $a1=array("a"=>array("red"),"b"=>array("green","blue"),); $a2=array("a"=>array("yellow"),"b"=>array("black")); print_r(array_replace_recursive($a1,$a2)); ?>

Output Array ( [a] => Array ( [0] => yellow ) [b] => Array ( [0] => black [1] =>

blue ) )

Function array_replace()

Description The array_replace() function replaces the values of the first array with

the values from following arrays.

Tip: You can assign one array to the function, or as many as you like.

If a key from array1 exists in array2, values from array1 will be

replaced by the values from array2. If the key only exists in array1, it

will be left as it is (See Example 1 below).

Syntax array_replace(array1,array2,array3...)

Example <?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_replace($a1,$a2));

?>

Output Array ( [0] => blue [1] => yellow )

Function array_reverse()

Description The array_reverse() function returns an array in the reverse order.

Syntax array_reverse(array,preserve)

Page 25: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 25

Example <?php $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a)); ?>

Output Array ( [c] => Toyota [b] => BMW [a] => Volvo )

Function array_search()

Description The array_search() function search an array for a value and returns the key.

Syntax array_search(value,array,strict)

Example <?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_search("red",$a); ?>

Output a

Function array_shift()

Description The array_shift() function removes the first element from an array, and

returns the value of the removed element.

Syntax array_shift(array)

Example <?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_shift($a); print_r ($a); ?>

Output red

Array ( [b] => green [c] => blue )

Function array_slice()

Description The array_slice() function returns selected parts of an array.

Syntax array_slice(array,start,length,preserve)

Page 26: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 26

Example <?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?>

Output Array ( [0] => blue [1] => yellow [2] => brown )

Function array_splice()

Description The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements.

Syntax array_splice(array,start,length,array)

Example <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); array_splice($a1,0,2,$a2); print_r($a1); ?>

Output Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )

Function compact()

Description The compact() function creates an array from variables and their values.

Syntax compact(var1,var2...)

Example <?php $firstname = "Peter"; $lastname = "Griffin"; $age = "41"; $result = compact("firstname", "lastname", "age"); print_r($result); ?>

Output Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )

Page 27: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 27

Function current()

Description The current() function returns the value of the current element in an array.

Syntax current(array)

Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; ?>

Output Peter

Function each()

Description The each() function returns the current element key and value, and

moves the internal pointer forward.

Syntax each(array)

Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); print_r (each($people)); ?>

Output Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )

Function end()

Description The end() function moves the internal pointer to, and outputs, the last element in the array.

Syntax end(array)

Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; echo end($people); ?>

Page 28: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 28

Output Peter

Cleveland

Function extract()

Description The extract() function imports variables into the local symbol table from an array.

Syntax extract(array)

Example <?php $a = "Original"; $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse"); extract($my_array); echo "\$a = $a; \$b = $b; \$c = $c"; ?>

Output $a = Cat; $b = Dog; $c = Horse

Function in_array()

Description The in_array() function searches an array for a specific value.

Syntax in_array(search,array,type)

Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) { echo "Match found"; } else { echo "Match not found"; } ?>

Output Match found

Page 29: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 29

Function Key()

Description The key() function returns the element key from the current internal

pointer position.

This function returns FALSE on error.

Syntax Key(array)

Example <?php $people=array("Peter","Joe","Glenn","Cleveland"); echo "The key from the current position is: " . key($people); ?>

Output The key from the current position is: 0

array_change_key_case — Changes the case of all keys in an array

array_chunk — Split an array into chunks

array_column — Return the values from a single column in the input array

array_combine — Creates an array by using one array for keys and another for its values

array_count_values — Counts all the values of an array

array_diff_assoc — Computes the difference of arrays with additional index check

array_diff_key — Computes the difference of arrays using keys for comparison

array_diff_uassoc — Computes the difference of arrays with additional index check which is

performed by a user supplied callback function

array_diff_ukey — Computes the difference of arrays using a callback function on the keys for

comparison

array_diff — Computes the difference of arrays

array_fill_keys — Fill an array with values, specifying keys

array_fill — Fill an array with values

array_filter — Filters elements of an array using a callback function

array_flip — Exchanges all keys with their associated values in an array

array_intersect_assoc — Computes the intersection of arrays with additional index check

array_intersect_key — Computes the intersection of arrays using keys for comparison

array_intersect_uassoc — Computes the intersection of arrays with additional index check,

compares indexes by a callback function

array_intersect_ukey — Computes the intersection of arrays using a callback function on the

keys for comparison

Page 30: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 30

array_intersect — Computes the intersection of arrays

array_multisort — Sort multiple or multi-dimensional arrays

array_pad — Pad array to the specified length with a value

array_pop — Pop the element off the end of array

array_product — Calculate the product of values in an array

array_push — Push one or more elements onto the end of array

array_rand — Pick one or more random entries out of an array

array_reduce — Iteratively reduce the array to a single value using a callback function

array_replace_recursive — Replaces elements from passed arrays into the first array

recursively

array_sum — Calculate the sum of values in an array

array_udiff_assoc — Computes the difference of arrays with additional index check, compares

data by a callback function

array_udiff_uassoc — Computes the difference of arrays with additional index check,

compares data and indexes by a callback function

array_udiff — Computes the difference of arrays by using a callback function for data

comparison

array_uintersect_assoc — Computes the intersection of arrays with additional index check,

compares data by a callback function

array_uintersect_uassoc — Computes the intersection of arrays with additional index check,

compares data and indexes by a callback functions

array_uintersect — Computes the intersection of arrays, compares data by a callback function

array_unique — Removes duplicate values from an array

array_unshift — Prepend one or more elements to the beginning of an array

array_values — Return all the values of an array

array_walk_recursive — Apply a user function recursively to every member of an array

array_walk — Apply a user supplied function to every member of an array

array — Create an array

arsort — Sort an array in reverse order and maintain index association

asort — Sort an array and maintain index association

krsort — Sort an array by key in reverse order

ksort — Sort an array by key

list — Assign variables as if they were an array

natcasesort — Sort an array using a case insensitive "natural order" algorithm

natsort — Sort an array using a "natural order" algorithm

next — Advance the internal array pointer of an array

Page 31: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 31

pos — Alias of current

prev — Rewind the internal array pointer

range — Create an array containing a range of elements

reset — Set the internal pointer of an array to its first element

rsort — Sort an array in reverse order

shuffle — Shuffle an array

sizeof — Alias of count

sort — Sort an array

uasort — Sort an array with a user-defined comparison function and maintain index

association

uksort — Sort an array by keys using a user-defined comparison function

usort — Sort an array by values using a user-defined comparison function

Page 32: Additional Functions of PHP – by Rocky Sir › downloads › Must_Refer_phpf… · Additional Functions of PHP – by Rocky Sir Company URL: Page 3 Format Description Example a

Additional Functions of PHP – by Rocky Sir

Company URL: http://suvenconsultants.com Page 32

Assignments: (Must be done by each level 2 WT student)

1) Display a date and time in this format -> "dd/mm/yyyy HH:MM".

2) Show the date 2 weeks further than current week.

3) Display all Sunday's date in the year of 2015.

4) Display time of Dubai.

5) The date of birth should be taken as input from the user. A user's age should

be calculated.

6) Calculate a no. of days between today’s date and Dec 31st 2015.

7) First allow a user to Login. After Login set a cookie to a value of a name of a

user entered during login.

8) Check if cookie is set or not.

9) Generate a PHP backtrace of a simple php function.

10) Create a user defined error such as if the length of input type text is

greater than "20" than it should give an fatal error.

11) Generate an user defined error if a variable does not exists.

12) Trigger an exception if the length of the string is greater than 10.

13) Create an array and sort it in a reverse order.

14) This is an given array array("a", "b", "c", "d", "e"). The output should be

Array([2] => c,[3] => d).

15) Create an array and take a value from the user and check if that value is

present in array.

16) This is an given array array(2, 4, 6, 8). The output should be an addition of

all values.