Praful Kumar Web page - PHP Functions List
|
|
1. 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.
// 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");
|
2. strcmp (PHP 4, PHP 5)
strcmp — Binary safe string comparison
Description
int strcmp ( string $str1, string $str2 )
Note that this comparison is case sensitive.
|
3. str_shuffle (PHP 4 >= 4.3.0, PHP 5)
str_shuffle — Randomly shuffles a string
Description
string str_shuffle ( string $str )
str_shuffle() shuffles a string. One permutation of all possible is created.
$str = 'abcdef';
$shuffled = str_shuffle($str);
// This will echo something like: bfdaec
echo $shuffled;
|
4. str_split (PHP 5)
str_split — Convert a string to an array
Description
array str_split ( string $string [, int $split_length] )
Converts a string to an array.
If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.
FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
|
5. strcasecmp (PHP 4, PHP 5)
strcasecmp — Binary safe case-insensitive string comparison
Description
int strcasecmp ( string $str1, string $str2 )
Binary safe case-insensitive string comparison.
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
|
6. strpos (PHP 4, PHP 5)
strpos — Find position of first occurrence of a string
Description
int strpos ( string $haystack, mixed $needle [, int $offset] )
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used.
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
|
7. strrchr (PHP 4, PHP 5)
strrchr — Find the last occurrence of a character in a string
Description
string strrchr ( string $haystack, string $needle )
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);
// get everything after last newline
$text = "Line 1nLine 2nLine 3";
$last = substr(strrchr($text, 10), 1 );
|
8. strrev (PHP 4, PHP 5)
strrev — Reverse a string
Description
string strrev ( string $string )
Returns string, reversed.
echo strrev("Hello world!"); // outputs "!dlrow olleH"
|
9. strripos (PHP 5)
strripos — Find position of last occurrence of a case-insensitive string in a string
Description
int strripos ( string $haystack, string $needle [, int $offset] )
Find position of last occurrence of a case-insensitive string in a string. Unlike strrpos(), strripos() is case-insensitive.
$haystack = 'ababcd';
$needle = 'aB';
$pos = strripos($haystack, $needle);
if ($pos === false) {
echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
echo "Congratulations!n";
echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
|
10. strrpos (PHP 4, PHP 5)
strrpos — Find position of last occurrence of a char in a string
Description
int strrpos ( string $haystack, string $needle [, int $offset] )
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character in PHP 4. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns FALSE.
It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
// in PHP 4.0.0 and newer:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
// not found...
}
// in versions older than 4.0.0:
$pos = strrpos($mystring, "b");
if (is_bool($pos) && !$pos) {
// not found...
}
|
11. strstr (PHP 4, PHP 5)
strstr — Find first occurrence of a string
Description
string strstr ( string $haystack, string $needle, bool $before_needle )
Returns part of haystack string from the first occurrence of needle to the end of haystack.
Note: This function is case-sensitive. For case-insensitive searches, use stristr().
Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
|
12. 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.
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
|
13. strtoupper (PHP 4, PHP 5)
strtoupper — Make a string uppercase
Description
string strtoupper ( string $string )
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
|
14. 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.
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, ; // abcdef
echo substr('abcdef', -1, 1); // f
// Accessing single characters in a string
// can also be achived using "curly braces"
$string = 'abcdef';
echo $string{0}; // a
echo $string{3}; // d
echo $string{strlen($string)-1}; // f
|
15. substr_compare (PHP 5)
substr_compare — Binary safe comparison of 2 strings from an offset, up to length characters
Description
int substr_compare ( string $main_str, string $str, int $offset [, int $length [, bool $case_insensitivity]] )
substr_compare() compares main_str from position offset with str up to length characters.
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
|
16. substr_count (PHP 4, PHP 5)
substr_count — Count the number of substring occurrences
Description
int substr_count ( string $haystack, string $needle [, int $offset [, int $length]] )
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
Note: This function doesn't count overlapped substrings. See the example below!
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
echo substr_count($text, 'is', 3); // the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3, 3); // the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 5, 10); // generates a warning because 5+10 > 14
$text2 = 'gcdgcdgcd'; // prints only 1, because it doesn't count overlapped subtrings
|
17. substr_replace (PHP 4, PHP 5)
substr_replace — Replace text within a portion of a string
Description
mixed substr_replace ( mixed $string, string $replacement, int $start [, int $length] )
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var
n";
/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "
n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "
n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "
n";
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "
n";
echo substr_replace($var, 'bob', -7, -1) . "
n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "
n";
|
18. ucfirst (PHP 4, PHP 5)
ucfirst — Make a string's first character uppercase
Description
string ucfirst ( string $str )
Returns a string with the first character of str capitalized, if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
|
19. ucwords (PHP 4, PHP 5)
ucwords — Uppercase the first character of each word in a string
Description
string ucwords ( string $str )
Returns a string with the first character of each word in str capitalized, if that character is alphabetic.
The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).
$foo = 'hello world!';
$foo = ucwords($foo); // Hello World!
$bar = 'HELLO WORLD!';
$bar = ucwords($bar); // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
|
20. array_diff (PHP 4 >= 4.0.1, PHP 5)
array_diff — Computes the difference of arrays
Description
array array_diff ( array $array1, array $array2 [, array $ ...] )
Compares array1 against array2 and returns the difference.
Examples
Example 248. array_diff() example
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
|
21. array_diff_key (PHP 5 >= 5.1.0)
array_diff_key — Computes the difference of arrays using keys for comparison
Description
array array_diff_key ( array $array1, array $array2 [, array $...] )
Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => ;
var_dump(array_diff_key($array1, $array2));
|
22. array_diff_uassoc (PHP 5)
array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
Description
array array_diff_uassoc ( array $array1, array $array2 [, array $..., callback $key_compare_func] )
Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.
Unlike array_diff_assoc() an user supplied callback function is used for the indices comparision, not internal function.
function key_compare_func($a, $b)
{
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
The above example will output:
Array( [b] => brown [c] => blue [0] => red )
|
23. array_pad (PHP 4, PHP 5)
array_pad — Pad array to the specified length with a value
Description
array array_pad ( array $input, int $pad_size, mixed $pad_value )
array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place. It is possible to add most 1048576 elements at a time.
$input = array(12, 10, 9);
$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)
$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)
$result = array_pad($input, 2, "noop");
// not padded
|
24. array_pop (PHP 4, PHP 5)
array_pop — Pop the element off the end of array
Description
mixed array_pop ( array &$array )
array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.
Note: This function will reset() the array pointer after use.
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
|
25. array_push (PHP 4, PHP 5)
array_push — Push one or more elements onto the end of array
Description
int array_push ( array &$array, mixed $var [, mixed $...] )
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
$array[] = $var;
repeated for each var.
Returns the new number of elements in the array.
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
|
26. array_rand (PHP 4, PHP 5)
array_rand — Pick one or more random entries out of an array
Description
mixed array_rand ( array $input [, int $num_req] )
array_rand() is rather useful when you want to pick one or more random entries out of an array. It takes an input array and an optional argument num_req which specifies how many entries you want to pick - if not specified, it defaults to 1.
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "n";
echo $input[$rand_keys[1]] . "n";
|
27. array_reduce (PHP 4 >= 4.0.5, PHP 5)
array_reduce — Iteratively reduce the array to a single value using a callback function
Description
mixed array_reduce ( array $input, callback $function [, int $initial] )
array_reduce() applies iteratively the function function to the elements of the array input, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. If the array is empty and initial is not passed, array_reduce() returns NULL.
function rsum($v, $w) {
$v += $w;
return $v; }
function rmul($v, $w) {
$v *= $w;
return $v; }
$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
This will result in $b containing 15, $c containing 1200 (= 10*1*2*3*4*5), and $d containing 1.
|
28. array_reverse (PHP 4, PHP 5)
array_reverse — Return an array with elements in reverse order
Description
array array_reverse ( array $array [, bool $preserve_keys] )
array_reverse() takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE.
$input = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:
Array([0] => Array([0] =>green [1] => red)[1] => 4[2] => php)
Array([2] => Array([0] => green[1] => red)[1] => 4[0] => php)
|
29. array_search (PHP 4 >= 4.0.5, PHP 5)
array_search — Searches the array for a given value and returns the corresponding key if successful
Description
mixed array_search ( mixed $needle, array $haystack [, bool $strict] )
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
Note: If needle is a string, the comparison is done in a case-sensitive manner.
Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.
If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack.
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
|
30. 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.
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
|
31. array_slice (PHP 4, PHP 5)
array_slice — Extract a slice of the array
Description
array array_slice ( array $array, int $offset [, int $length [, bool $preserve_keys]] )
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
Note that array_slice() will reorder and reset the array indices by default. Since PHP 5.0.2, you can change this behaviour by setting preserve_keys to TRUE.
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
print_r(array_slice($input, 2, -1)); // note the differences in the array keys
print_r(array_slice($input, 2, -1, true));
The above example will output:
Array([0] => c[1] => d)
Array([2] => c[3] => d)
|
32. array_splice (PHP 4, PHP 5)
array_splice — Remove a portion of the array and replace it with something else
Description
array array_splice ( array &$input, int $offset [, int $length [, array $replacement]] )
array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. It returns an array containing the extracted elements. Note that numeric keys in input are not preserved.
If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.
If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.
If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Note that keys in replacement array are not preserved. If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.
The following statements change the values of $input the same way:
Table 21. array_splice() equivalents
array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y))
array_pop($input) array_splice($input, -1)
array_shift($input) array_splice($input, 0, 1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // for arrays where key equals offset array_splice($input, $x, 1, $y)
Returns the array consisting of removed elements.
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// "blue", "black", "maroon")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// "blue", "purple", "yellow");
|
33. array_sum (PHP 4 >= 4.0.4, PHP 5)
array_sum — Calculate the sum of values in an array
Description
number array_sum ( array $array )
array_sum() returns the sum of values in an array as an integer or float.
$a = array(2, 4, 6, ;
echo "sum(a) = " . array_sum($a) . "n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "n";
The above example will output:
sum(a) = 20
sum(b) = 6.9
|
34. 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.
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
The above example will output:
Array([0] => apple[1] => raspberry[2] => orange[3] => banana)
|
35. trim (PHP 4, PHP 5)
trim — Strip whitespace (or other characters) from the beginning and end of a string
Description
string trim ( string $str [, string $charlist] )
This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
• " " (ASCII 32 (0x20)), an ordinary space.
• "t" (ASCII 9 (0x09)), a tab.
• "n" (ASCII 10 (0x0A)), a new line (line feed).
• "r" (ASCII 13 (0x0D)), a carriage return.
• "�" (ASCII 0 (0x00)), the NUL-byte.
• "x0B" (ASCII 11 (0x0B)), a vertical tab.
$text = "ttThese are a few words ... ";
$binary = "x09Example stringx0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "n";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " t.");
var_dump($trimmed);
$trimmed = trim($hello, "Hdle");
var_dump($trimmed);
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "x00..x1F");
var_dump($clean);
The above example will output:
string(32) " These are a few words ... "
string(16) " Example string
"
string(11) "Hello World"
string(28) "These are a few words ..."
string(24) "These are a few words "
string(5) "o Wor"
string(14) "Example string"
|
36. 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.
$text = "ttThese are a few words ... ";
$binary = "x09Example stringx0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "n";
$trimmed = ltrim($text);
var_dump($trimmed);
$trimmed = ltrim($text, " t.");
var_dump($trimmed);
$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);
// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean = ltrim($binary, "x00..x1F");
var_dump($clean);
The above example will output:
string(32) " These are a few words ... "
string(16) " Example string
"
string(11) "Hello World"
string(30) "These are a few words ... "
string(30) "These are a few words ... "
string(7) "o World"
string(15) "Example string
"
|
37. rtrim (PHP 4, PHP 5)
rtrim — Strip whitespace (or other characters) from the end of a string
Description
string rtrim ( string $str [, string $charlist] )
This function returns a string with whitespace stripped from the end of str.
$text = "ttThese are a few words ... ";
$binary = "x09Example stringx0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "n";
$trimmed = rtrim($text);
var_dump($trimmed);
$trimmed = rtrim($text, " t.");
var_dump($trimmed);
$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);
// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "x00..x1F");
var_dump($clean);
The above example will output:
string(32) " These are a few words ... "
string(16) " Example string
"
string(11) "Hello World"
string(30) " These are a few words ..."
string(26) " These are a few words "
string(9) "Hello Wor"
string(15) " Example string"
|
38. chop (PHP 4, PHP 5)
chop — Alias of rtrim()
Description
This function is an alias of: rtrim().
Notes
Note: chop() is different than the Perl chop() function, which removes the last character in the string.
|
39. chown (PHP 4, PHP 5)
chown — Changes file owner
Description
bool chown ( string $filename, mixed $user )
Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.
Notes
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
|
40. chr (PHP 4, PHP 5)
chr — Return a specific character
Description
string chr ( int $ascii )
Returns a one-character string containing the character specified by ascii.
This function complements ord().
$str = "The string ends in escape: ";
$str .= chr(27); /* add an escape character at the end of $str */
/* Often this is more useful */
$str = sprintf("The string ends in escape: %c", 27);
|
41. chroot (PHP 4 >= 4.0.5, PHP 5)
chroot — Change the root directory
Description
bool chroot ( string $directory )
Changes the root directory of the current process to directory.
This function is only available if your system supports it and you're using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.
|
42. chunk_split (PHP 4, PHP 5)
chunk_split — Split a string into smaller chunks
Description
string chunk_split ( string $body [, int $chunklen [, string $end]] )
Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters.
|
43. copy (PHP 4, PHP 5)
copy — Copies file
Description
bool copy ( string $source, string $dest [, resource $context] )
Makes a copy of the file source to dest.
If you wish to move a file, use the rename() function.
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...n";
}
|
44. 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.
Note: The optional mode parameter is available as of PHP 4.2.0.
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0. count() does not detect infinite recursion.
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.
Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
// $result == 3
$result = count(null);
// $result == 0
$result = count(false);
// $result == 1
$food = array('fruits' => 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
|
45. count_chars (PHP 4, PHP 5)
count_chars — Return information about characters used in a string
Description
mixed count_chars ( string $string [, int $mode] )
Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways.
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of "" , chr($i) , "" in the string.n";
}
The above example will output:
There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.
|
46. empty (PHP 4, PHP 5)
empty — Determine whether a variable is empty
Description
bool empty ( mixed $var )
Determine whether a variable is considered to be empty.
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
|
47. end (PHP 4, PHP 5)
end — Set the internal pointer of an array to its last element
Description
mixed end ( array &$array )
end() advances array's internal pointer to the last element, and returns its value.
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
|
48. ereg (PHP 4, PHP 5)
ereg — Regular expression match
Description
int ereg ( string $pattern, string $string [, array &$regs] )
Searches a string for matches to the regular expression given in pattern in a case-sensitive way.
|
49. ereg_replace (PHP 4, PHP 5)
ereg_replace — Replace regular expression
Description
string ereg_replace ( string $pattern, string $replacement, string $string )
This function scans string for matches to pattern, then replaces the matched text with replacement.
$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "1was", $string);
echo ereg_replace("(( )is)", "2was", $string);
|
50. eregi (PHP 4, PHP 5)
eregi — Case insensitive regular expression match
Description
int eregi ( string $pattern, string $string [, array &$regs] )
This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters
$string = 'XYZ';
if (eregi('z', $string)) {
echo "'$string' contains a 'z' or 'Z'!";
}
|
51. eregi_replace (PHP 4, PHP 5)
eregi_replace — Replace regular expression case insensitive
Description
string eregi_replace ( string $pattern, string $replacement, string $string )
This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '12';
$body = eregi_replace($pattern, $replacement, $body);
|
52. 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.
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
|
53. 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.
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
|
54. fclose (PHP 4, PHP 5)
fclose — Closes an open file pointer
Description
bool fclose ( resource $handle )
The file pointed to by handle is closed.
$handle = fopen('somefile.txt', 'r');
fclose($handle);
|
55. fopen (PHP 4, PHP 5)
fopen — Opens file or URL
Description
resource fopen ( string $filename, string $mode [, bool $use_include_path [, resource $context]] )
fopen() binds a named resource, specified by filename, to a stream.
$handle = fopen("c:datainfo.txt", "r");
Table 93. A list of possible modes for fopen() using mode
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
Note: Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use n as the line ending character, Windows based systems use rn as the line ending characters and Macintosh based systems use r as the line ending character.
If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".
Windows offers a text-mode translation flag ('t') which will transparently translate n to rn when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.
The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.
If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with rn characters.
Note: For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().
Note: Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.
|
56. fgets (PHP 4, PHP 5)
fgets — Gets line from file pointer
Description
string fgets ( resource $handle [, int $length] )
Gets a line from file pointer.
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
|
57. file (PHP 4, PHP 5)
file — Reads entire file into an array
Description
array file ( string $filename [, int $flags [, resource $context]] )
Reads an entire file into an array.
Note: You can use file_get_contents() to return the contents of a file as a string.
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
n";
}
// Another example, let's get a web page into a string. See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
|
58. file_get_contents (PHP 4 >= 4.3.0, PHP 5)
file_get_contents — Reads entire file into a string
Description
string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen]]]] )
This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
|
59. file_exists (PHP 4, PHP 5)
file_exists — Checks whether a file or directory exists
Description
bool file_exists ( string $filename )
Checks whether a file or directory exists.
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
|
60. filesize (PHP 4, PHP 5)
filesize — Gets file size
Description
int filesize ( string $filename )
Gets the size for the given file.
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
|
61. filetype (PHP 4, PHP 5)
filetype — Gets file type
Description
string filetype ( string $filename )
Returns the type of the given file.
echo filetype('/etc/passwd'); // file
echo filetype('/etc/'); // dir
|
62. floor (PHP 4, PHP 5)
floor — Round fractions down
Description
float floor ( float $value )
Returns the next lowest integer value by rounding down value if necessary.
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
|
63. fread (PHP 4, PHP 5)
fread — Binary-safe file read
Description
string fread ( resource $handle, int $length )
fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:
• length bytes have been read
• EOF (end of file) is reached
• a packet becomes available (for network streams)
• 8192 bytes have been read (after opening userspace stream)
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
|
64. fstat (PHP 4, PHP 5) fstat — Gets information about a file using an open file pointer Description
array fstat ( resource $handle )
Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.
$fp = fopen("/etc/passwd", "r"); // open a file
$fstat = fstat($fp); // gather statistics
fclose($fp); // close the file
print_r(array_slice($fstat, 13)); // print only the associative part
The above example will output something similar to:
Array([dev] => 771[ino] => 488704[mode] => 33188[nlink] => 1[uid] => 0 [gid] => 0[rdev] => 0[size] => 1114[atime] => 1061067181[mtime] => 1056136526[ctime] => 1056136526[blksize] => 4096[blocks] =>
|
|
|
|