Functions in PHP
To define functions we have the instruction function
After this reserved word is placed the name of the function followed by a list of arguments delimited by parentheses and separated by commas
Arguments
The argument step is optional and in some cases there may be functions that lack them
For example, the function phpinfo has no arguments
This function shows us information regarding the PHP module we are using and always returns the integer value 1
Type of arguments
Starting with PHP 7 you can optionally declare the type of arguments passed to the function
Supports types string, int, float, array, callable and clases
If the function user misinculated them or uses another type of data, PHP will return an error message indicating it
Default value arguments
Sometimes we need an argument to have a value, to avoid an error, even if the function user does not enter it
Note that default arguments become optional and that all arguments to the left of the first default value are required
Arguments by value or by reference
When we pass a value to a function, even if we modify it, when we exit the function it will retain its original value
This is the default situation and is called a argument by value
Since an in memory copy of the variable is used and when the function is exited, that copy of the variable is destroyed
In the event that we want changes made to the value of the variable to be preserved after exiting the function, we must use the symbol & in front of the variable name
This situation is called a argument by reference
Since a reference to the variable is used in memory, working directly on the variable and when the function is exited, all changes remain
Until PHP 5.0.5 it was possible to indicate that a function was by reference using the symbol & in front of the function name
However, as of PHP 5.3.0 it would go on to indicate with a message call-time pass-by-reference that its use was obsolete
As of PHP 5.4.0 it was completely removed and currently produces a fatal error
That is, only the symbol can be used & when passing arguments, never in the function name
We can only pass by reference:
- Variables
- References returned from functions
The return statement
The statement return it is the one that allows you to return the result of a function
Starting with PHP 7, you can optionally declare the type returned by the function
Supports types string, int, float, array, callable and clases
To declare the type, the symbol will be written : after the parentheses that follow the arguments and before the start key {
Functions are predefined by the language
Display functions
Echo
The function echo is used to send the output of its arguments to the browser
We have continuously used it in previous examples
It has the format:
It has the following characteristics:
-
We can do without the parentheses in their use, since they are optional
-
Converts all information to string before sending it to the browser
-
If we use several echo in a row, we will find that the result concatenates it in the same line
To solve it we will have to use the HTML tag <br/>
to jump the line -
If we use several in a row, we will find that the result does not add a space at the end and therefore the content could show incomprehensible texts, lacking that space
To solve it we will have to add a space at the end of the first echo or at the beginning of the next echo
printf
The function printf serves to send the output of your arguments to the browser in a format
It has the format:
To format a text you have to enter the following formatting characters preceded by the symbol %:
Format characters for text | |
Character | Description |
% |
Literal percentage character Does not require an argument |
b |
The argument is treated as a value of type integer and presented as a binary number |
c |
The argument is treated as a value of type integer and presented as the character with that ASCII value |
d |
The argument is treated as an integer type value and presented as a decimal (signed) number |
e |
The argument is treated with scientific notation (for example 1.2e+2) The precision specifier indicates the number of digits after the decimal point as of PHP 5.2.1. In previous versions, it was taken as the number of significant digits (minus one) |
E |
Like %e but it uses the capital letter (for example 1.2E+2) |
f |
The argument is treated as a float type value and presented as a floating point number (considering locale) |
F |
The argument is treated as a float type value and presented as a floating point number (regardless of locale) Available since PHP 4.3.10 and PHP 5.0.3. |
g |
Like %e and %f |
G |
Like que %E and %f |
o |
The argument is treated as a value of type integer and presented as an octal number |
s |
The argument is treated and presented as a string |
u |
The argument is treated as an integer type value and presented as an unsigned decimal number |
x |
The argument is treated as a value of type integer and presented as a hexadecimal number (with lowercase letters) |
X |
The argument is treated as a value of type integer and presented as a hexadecimal number (with capital letters) |
sprintf
The function sprintf serves to assign to its arguments, in a formatted way, the return variable
It has the same format as printf and supports the same formats
print_r
The function print_r serves to send the output of their arguments to the browser, displaying understandable information by people about the arguments
It's useful to be able to debug our code
It has the following format:
We can use it to see the full contents of an array
Functions for strings
Let's look at some of the most everyday functions for strings
If you need more, the full list can be found in the PHP manual
Uppercase and lowercase
The function strtoupper returns a copy of the string in uppercase
The function strtolower returns a lowercase copy of the string
Extract String
The function substr serves to extract a substring from the string we pass it as an argument
It has the following format:
Where $start is the starting position of the substring and $length the length that the substring will have
It can be useful when we need to extract a word from a text and we know in advance its position and length
Keep in mind that the position $start should start at 0
String length
The function strlen is used to count the length of the string
It has the following format:
Resuming the string from the example above
Position of a character in the String
The function strpos serves to find the position of a particular character in the string
It has the following format:
Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $offset, which is optional, is the starting number you start looking for
Keep in mind that the starting position starts at zero
Unless we specify the value of $offset
Find a text
The function strstr serves to find the first occurrence of a string
It has the following format:
It is very similar to substr, but it saves us having to use strpos intermediate
Array functions
Let's see some of the functions for arrays of daily use
If you need more, the full list can be found in the PHP manual
Count the number of items
The function count serves to count the total number of elements
It has the following format:
Optionally we can use the argument $mode which by default uses the value COUNT_NORMAL (counts elements sequentially) and for multidimensional arrays COUNT_RECURSIVE (count the elements recursively, that is, it goes through all the multidimensional arrays and adds the total number of elements)
Find a value in the array
Check if a value exists
The function in_array is used to check if a value exists inside an array
It has the following format:
Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $strict, which is optional, if is TRUE will check the types of $needle in $haystack
If $needle is a string, the comparison is made considering the case
Finding the first value
The function array_search serves to find the first value, if exists, within an array
It has the following format:
Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $strict, which is optional, if is TRUE will check the types of $needle in $haystack
If $needle is a string, the comparison is made considering the case
You have to be careful with the values returned by this function because it can return the Boolean value FALSE, but you can also return a non Boolean value that evaluates to FALSE
In versions prior to PHP 4.2.0 returned NULL in the event of a failure, rather than FALSE
Starting with PHP 5.3.0 returns NULL if you pass invalid parameters
Date formats
PHP doesn't have a date type
To work with dates use strings formatted with UNIX style timestamps
These timestamps are an integer value measured in seconds that begin to count from January 1, 1970
Timestamps
To get the current timestamp we can use the function time which has the following format:
The obtained value is easy to manipulate, as we can add multiples to it:
- 3600 to add hours
- 86400 to add days
- 604800 to add weeks
Formatted string
We can also use a format string to work with dates using the function date which has the following format:
Where $format is the string with the format we want to use, $timestamp, which is optional and by default takes the function time, is a UNIX timestamp
To format a date you have to enter the following formatting characters:
Date formatting characters | |
Character | Description |
d |
Day of the month, 2 digits with leading zeros |
D |
String for the day, three letters |
j |
Day of the month without leading zeros |
l (lowercase L) |
String for the day of the week |
N |
Numerical representation ISO-8601 of the day of the week Added in PHP 5.1.0. |
S |
Ordinal suffix for the day of the month, 2 characters |
w |
Numerical representation of the day of the week |
z |
The day of the year (starting with 0) |
W |
Week number of the year ISO-8601, weeks start on Monday |
F |
A full textual representation of a month, such as January or March |
m |
Numerical representation of a month, with leading zeros |
M |
A short textual representation of one month, three letters |
n |
Numerical representation of a month, without leading zeros |
t |
Number of days of the given month |
L |
If it is a leap year |
o |
Year according to the week number ISO-8601 This has the same value as Y, except that if the week number belongs to the previous or next year, that year is used instead Added in PHP 5.1.0. |
Y |
A complete numerical representation of a year, 4 digits |
y |
A two digit representation of a year |
a |
lowercase am or pm |
A |
uppercase am or pm |
B |
Internet time |
g |
12 hour one hour format with no leading zeros |
G |
24 hour one hour format with no leading zeros |
h |
12 hour one hour format with leading zeros |
H |
24 hour one hour format with leading zeros |
i |
Minutes with leading zeros |
s |
Seconds with leading zeros |
u |
Microseconds Added in PHP 5.2.2. date() will always generate 000000 when taking a parameter of type integer, while DateTime::format() supports microseconds if DateTime was created with microseconds |
v |
Milliseconds Added in PHP 7.0.0. The same observation as for u |
e |
Time zone identifier Added in PHP 5.1.0. |
I (capital i) |
The date is in summer time or not |
O |
Greenwich Mean Time (GMT) difference in hours |
P |
Difference from Greenwich Mean Time (GMT) with two points between hours and minutes Added in PHP 5.1.3. |
T |
Time zone abbreviation |
Z |
Time zone index in seconds The index for time zones west of UTC is always negative, and for those east of UTC it is always positive |
c |
Date ISO 8601 Added in PHP 5 |
r |
Date in the format RFC 2822 |
U |
Seconds in UNIX format (January 1, 1970 00:00:00 GMT) |
Get a date from a string
Using a delimiter
From a string we can pick up a date using the function explode which has the following format:
Where $delimiter is the character used to delimit the values, $string the string that contains the date we want to manipulate and $limit an optional value whose default value is 1, which indicates the maximum number of return values
If $limit negative will return all values by removing the value of $limit from the end
And if it's 0 it's going to be treated like 1
And then we'll use the function mktime to create the UNIX type timestamp, which has the following format:
Where $hour is the hour, $minute is the minutes, $second, the seconds, $month is the month, $day is the day $year is the year and $is_dst is summer time or not (-1 if is not)
All parameters are optional, in case you don't enter any, the result of the function will be taken time
Starting with 5.1, when the call is made without arguments, it issues a warning of type E_STRICT: use function time() in its place
Converting a string to date format
From a string we can pick up a date using the function strtotime which has the following format:
Where $time is the string from which we want to get the date, $now, which is optional and by default takes the function time, is a UNIX timestamp
Starting with PHP 5.0.0, microseconds started to be allowed, but were ignored
In PHP 5 up to 5.0.2, now and other relative moments are wrongly computed like today's midnight
This differs between versions where it is computed as the current moment
As of PHP 5.1.0 it shows the error E_STRICT and E_NOTICE when errors occur with time zones
And returns FALSE if fails, instead of -1
In PHP 5 through 5.2.7, requests for an occurrence of a given day of the week in a month where that day of the week was the first day of the month, incorrectly added a week to the returned timestamp
This was fixed in 5.2.7 and is maintained in later versions
Before PHP 5.3.0, 24:00 was not a valid format and returned FALSE
The relative time formats that were supplied to the parameter $time such as this week, previous week, last week, and next week were interpreted as a period of 7 days relative to the current date and time, rather than a period of the week from Monday to Sunday