"Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid." – Albert Einstein

PHP: Functions



1. nl2br (PHP 4, PHP 5)
nl2br — Inserts HTML line breaks before all newlines in a string
Description: string nl2br ( string $string )
Returns string with ‘
‘ inserted before all newlines.

2. Htmlspecialchars (PHP 4, PHP 5)
htmlspecialchars — Convert special characters to HTML entities
<?php
$new = htmlspecialchars(“Test“, ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>

3. touch (PHP 4, PHP 5)
touch — Sets access and modification time of file

4. set_time_limit (PHP 4, PHP 5)
set_time_limit — Limits the maximum execution time
Description
void set_time_limit ( int $seconds )
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

5. intval (PHP 4, PHP 5)
intval — Get the integer value of a variable
Description
int intval ( mixed $var [, int $base] )
Returns the integer value of var, using the specified base for the conversion (the default is base 10).

6. explode (PHP 4, PHP 5)
explode — Split a string by string
Description
array explode ( string $delimiter, string $string [, int $limit] )
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

7. implode (PHP 4, PHP 5)
implode — Join array elements with a string
Description
string implode ( string $glue, array $pieces )
Join array elements with a glue string.
Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.
Parameters
glue
Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.

8. split (PHP 4, PHP 5)
split — Split string into array by regular expression
Description
array split ( string $pattern, string $string [, int $limit] )
Splits a string into array by regular expression.
<?php
// Delimiters may be slash, dot, or hyphen
$date = “04/30/1973”;
list($month, $day, $year) = split(‘[/.-]’, $date);
echo “Month: $month; Day: $day; Year: $year
\n”;
?>

9. substr (PHP 4, PHP 5)
substr — Return part of a string
Description
string substr ( string $string, int $start [, int $length] )
Returns the portion of string specified by the start and length parameters.

10. str_replace (PHP 4, PHP 5)
str_replace — Replace all occurrences of the search string with the replacement string
Description
mixed str_replace ( mixed $search, mixed $replace, mixed $subject [, int &$count] )
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
<?php
// Provides:
$bodytag = str_replace(“%body%”, “black”, “”);

// Provides: Hll Wrld f PHP
$vowels = array(“a”, “e”, “i”, “o”, “u”, “A”, “E”, “I”, “O”, “U”);
$onlyconsonants = str_replace($vowels, “”, “Hello World of PHP”);
?>

11. array_intersect (PHP 4 >= 4.0.1, PHP 5)
array_intersect — Computes the intersection of arrays
Description
array array_intersect ( array $array1, array $array2 [, array $ …] )
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
“green”, “red”, “blue”);
$array2 = array(“b” => “green”, “yellow”, “red”);
$result = array_intersect($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[a] => green
[0] => red
)

12. mysql_info (PHP 4 >= 4.3.0, PHP 5, PECL mysql:1.0)
mysql_info — Get information about the most recent query
Description
string mysql_info ( [resource $link_identifier] )
Returns detailed information about the last query.

13. mysql_insert_id (PHP 4, PHP 5, PECL mysql:1.0)
mysql_insert_id — Get the ID generated from the previous INSERT operation
Description
int mysql_insert_id ( [resource $link_identifier] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.

14. mysql_list_fields (PHP 4, PHP 5, PECL mysql:1.0)
mysql_list_fields — List MySQL table fields
Description
resource mysql_list_fields ( string $database_name, string $table_name [, resource $link_identifier] )
Retrieves information about the given table name.
This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE ‘name’] statement instead.

15. mysql_list_fields (PHP 4, PHP 5, PECL mysql:1.0)
mysql_list_fields — List MySQL table fields
Description
resource mysql_list_fields ( string $database_name, string $table_name [, resource $link_identifier] )
Retrieves information about the given table name.
This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE ‘name’] statement instead.

16. mysql_close (PHP 4, PHP 5, PECL mysql:1.0)
mysql_close — Close MySQL connection
Description
bool mysql_close ( [resource $link_identifier] )
mysql_close() closes the non-persistent connection to the MySQL server that’s associated with the specified link identifier. If link_identifier isn’t specified, the last opened link is used.

17. strtolower (PHP 4, PHP 5)
strtolower — Make a string lowercase
Description
string strtolower ( string $str )
Returns string with all alphabetic characters converted to lowercase.
Note that ‘alphabetic’ is determined by the current locale. This means that in i.e. the default “C” locale, characters such as umlaut-A (Ä) will not be converted.

18. count (PHP 4, PHP 5)
count — Count elements in an array, or properties in an object
Description
int count ( mixed $var [, int $mode] )
Returns the number of elements in var, which is typically an array, since anything else will have one element.
For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, count(), which returns the return value for the count() function.
If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.
Caution
count() may return 0 for a variable that isn’t set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.
array(‘orange’, ‘banana’, ‘apple’),
‘veggie’ => array(‘carrot’, ‘collard’, ‘pea’));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

?>

19. is_array (PHP 4, PHP 5)
is_array — Finds whether a variable is an array
Description
bool is_array ( mixed $var )
Finds whether the given variable is an array.

The above example will output:

Array
not an Array

20. array_map (PHP 4 >= 4.0.6, PHP 5)
array_map — Applies the callback to the elements of the given arrays
Description
array array_map ( callback $callback, array $arr1 [, array $…] )
array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

This makes $b have:
Array
( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )

21. array_shift (PHP 4, PHP 5)
array_shift — Shift an element off the beginning of array
Description
mixed array_shift ( array &$array )
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won’t be touched. If array is empty (or is not an array), NULL will be returned.
Note: This function will reset() the array pointer after use.
Example . array_shift() example

This would result in $stack having 3 elements left:
Array( [0] => banana [1] => apple [2] => raspberry)
and orange will be assigned to $fruit.

22. array_key_exists (PHP 4 >= 4.0.7, PHP 5)
array_key_exists — Checks if the given key or index exists in the array
Description
bool array_key_exists ( mixed $key, array $search )
array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index. array_key_exists() also works on objects.
1, ‘second’ => 4);
if (array_key_exists(‘first’, $search_array)) {
echo “The ‘first’ element is in the array”;
}
?>

23. in_array (PHP 4, PHP 5)
in_array — Checks if a value exists in an array
Description
bool in_array ( mixed $needle, array $haystack [, bool $strict] )
Searches haystack for needle and returns TRUE if it is found in the array, FALSE otherwise.
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.
Note: If needle is a string, the comparison is done in a case-sensitive manner.
Note: In PHP versions before 4.2.0 needle was not allowed to be an array.
Example . in_array() example

24. array_merge (PHP 4, PHP 5)
array_merge — Merge one or more arrays
Description
array array_merge ( array $array1 [, array $array2 [, array $…]] )
array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.
Example . array_merge() example
“red”, 2, 4);
$array2 = array(“a”, “b”, “color” => “green”, “shape” => “trapezoid”, 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:
Array( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )

25. array_unique (PHP 4 >= 4.0.1, PHP 5)
array_unique — Removes duplicate values from an array
Description
array array_unique ( array $array )
array_unique() takes input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
The first element will be used.
Example . array_unique() example
“green”, “red”, “b” => “green”, “blue”, “red”);
$result = array_unique($input);
print_r($result);
?>
The above example will output:
Array( [a] => green [0] => red [1] => blue )

26. array_unshift (PHP 4, PHP 5)
array_unshift — Prepend one or more elements to the beginning of an array
Description
int array_unshift ( array &$array, mixed $var [, mixed $…] )
array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won’t be touched.
Returns the new number of elements in the array.
Example . array_unshift() example

The above example will output:
Array( [0] => apple [1] => raspberry [2] => orange [3] => banana)

27. array_values (PHP 4, PHP 5)
array_values — Return all the values of an array
Description
array array_values ( array $input )
array_values() returns all the values from the input array and indexes numerically the array.
Example . array_values() example
“XL”, “color” => “gold”);
print_r(array_values($array));
?>
The above example will output:
Array( [0] => XL [1] => gold )

28. preg_match_all (PHP 4, PHP 5)
preg_match_all — Perform a global regular expression match
Description
int preg_match_all ( string $pattern, string $subject, array &$matches [, int $flags [, int $offset]] )
Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.
After the first match is found, the subsequent searches are continued on from end of the last match.
Example . Getting all phone numbers out of some text.

Example . Find matching HTML tags (greedy)
<?php
// The \\2 is an example of backreferencing. This tells pcre that it must match the second set of parentheses in the regular expression. itself, which would be the ([\w]+) in this case. The extra backslash is
required because the string is in double quotes.
$html = “bold textclick me“;

preg_match_all(“/(]*>)(.*)()/”, $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
echo “matched: ” . $val[0] . “\n”;
echo “part 1: ” . $val[1] . “\n”;
echo “part 2: ” . $val[3] . “\n”;
echo “part 3: ” . $val[4] . “\n\n”;
}
?>
The above example will output:
matched: bold text
part 1: part 2: bold text part 3:

matched: click me
part 1: part 2: click me part 3:

29. preg_replace_callback (PHP 4 >= 4.0.5, PHP 5)
preg_replace_callback — Perform a regular expression search and replace using a callback
Description
mixed preg_replace_callback ( mixed $pattern, callback $callback, mixed $subject [, int $limit [, int &$count]] )
The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.
Example . preg_replace_callback() example

The above example will output:

April fools day is 04/01/2003
Last christmas was 12/24/2002

30. preg_match (PHP 4, PHP 5)

preg_match — Perform a regular expression match
Description
int preg_match ( string $pattern, string $subject [, array &$matches [, int $flags [, int $offset]]] )
Searches subject for a match to the regular expression given in pattern
Example 1728. Find the string of text “php”

31. ltrim (PHP 4, PHP 5)
ltrim — Strip whitespace (or other characters) from the beginning of a string
Description
string ltrim ( string $str [, string $charlist] )
Strip whitespace (or other characters) from the beginning of a string.

32. stripslashes (PHP 4, PHP 5)
stripslashes — Un-quote string quoted with addslashes()
Description
string stripslashes ( string $str )
Un-quotes a quoted string.
Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.
An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it’s on by default), and you aren’t inserting this data into a place (such as a database) that requires escaping. For example, if you’re simply outputting data straight from an HTML form.
Example . A stripslashes() example

Note: stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.
Example . Using stripslashes() on an array

The above example will output:

Array( [0] => f’oo [1] => b’ar [2] => Array ( [0] => fo’o [1] => b’ar ) )

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s