Home >Backend Development >PHP Tutorial >PHP functions commonly used in project development_PHP tutorial
Date operations
In order to facilitate storage, comparison and transmission, we usually need to use the strtotime() function to convert the date into a UNIX timestamp. The date() function is only used to convert the date into a commonly used time format when displayed to the user.
strtotime()
Function parses any English text datetime description into a Unix timestamp
eg:
<?php echo(strtotime("now")); echo(strtotime("3 October 2005")); echo(strtotime("+5 hours")); echo(strtotime("+1 week")); echo(strtotime("+1 week 3 days 7 hours 5 seconds")); echo(strtotime("next Monday")); echo(strtotime("last Sunday")); ?>
1138614504
1128290400
1138632504
1139219304
1139503709
1139180400
1138489200
date() function converts timestamps into common date formats
eg:
echo date('Y-m-d H:i:s',"1138614504");
Output:
2006-01-30 17:48:24
String operations
Sometimes you need to get part of a string, you need to use the string interception substr() function
The substr() function returns a part of the string
Syntax:
substr(string,start,length)
eg:
echo substr("Hello world!",6,5);
Output:
world
Array operations
Here are two very practical functions:
array_unique() removes the number of identical elements in the array
When the values of several array elements are equal, only the first element is retained and the other elements are deleted.
The key names in the returned array remain unchanged.
array_filter() deletes empty elements in the array
Syntax:
array array_filter ( array $input [, callable $callback = "" ] )
Pass each value in the input array to the callback function in turn. If the callback function returns TRUE, the current value of the input array will be included in the returned result array. The key names of the array remain unchanged.
Input is the array to be looped
callback is the callback function used. If no callback function is provided, all entries with a value equal to FALSE in input will be deleted (you can use this to delete empty elements in the array).
eg1:
<?php function odd($var){ return($var & 1); } $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); echo "Odd :\n"; print_r(array_filter($array1, "odd")); ?>
Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
eg2:
<?php $entry = array( 0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => '' ); print_r(array_filter($entry)); ?>
Array
(
[0] => foo
[2] => -1
)