PHP Reference

Must Watch!

MustWatch
https://www.w3schools.com/php/php_ref_overview.asp



Array Introduction

The array functions allow you to access and manipulate arrays. Simple and multi-dimensional arrays are supported.

Installation

The array functions are part of the PHP core. There is no installation needed to use these functions.

Array Functions

FunctionDescription
array()Creates an array
array_change_key_case()Changes all keys in an array to lowercase or uppercase
array_chunk()Splits an array into chunks of arrays
array_column()Returns the values from a single column in the input array
array_combine()Creates an array by using the elements from one "keys" array and one "values" array
array_count_values()Counts all the values of an array
array_diff()Compare arrays, and returns the differences (compare values only)
array_diff_assoc()Compare arrays, and returns the differences (compare keys and values)
array_diff_key()Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc()Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey()Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill()Fills an array with values
array_fill_keys()Fills an array with values, specifying keys
array_filter()Filters the values of an array using a callback function
array_flip()Flips/Exchanges all keys with their associated values in an array
array_intersect()Compare arrays, and returns the matches (compare values only)
array_intersect_assoc()Compare arrays and returns the matches (compare keys and values)
array_intersect_key()Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey()Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists()Checks if the specified key exists in the array
array_keys()Returns all the keys of an array
array_map()Sends each value of an array to a user-made function, which returns new values
array_merge()Merges one or more arrays into one array
array_merge_recursive()Merges one or more arrays into one array recursively
array_multisort()Sorts multiple or multi-dimensional arrays
array_pad()Inserts a specified number of items, with a specified value, to an array
array_pop()Deletes the last element of an array
array_product()Calculates the product of the values in an array
array_push()Inserts one or more elements to the end of an array
array_rand()Returns one or more random keys from an array
array_reduce()Returns an array as a string, using a user-defined function
array_replace()Replaces the values of the first array with the values from following arrays
array_replace_recursive()Replaces the values of the first array with the values from following arrays recursively
array_reverse()Returns an array in the reverse order
array_search()Searches an array for a given value and returns the key
array_shift()Removes the first element from an array, and returns the value of the removed element
array_slice()Returns selected parts of an array
array_splice()Removes and replaces specified elements of an array
array_sum()Returns the sum of the values in an array
array_udiff()Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc()Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc()Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect()Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc()Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique()Removes duplicate values from an array
array_unshift()Adds one or more elements to the beginning of an array
array_values()Returns all the values of an array
array_walk()Applies a user function to every member of an array
array_walk_recursive()Applies a user function recursively to every member of an array
arsort()Sorts an associative array in descending order, according to the value
asort()Sorts an associative array in ascending order, according to the value
compact()Create array containing variables and their values
count()Returns the number of elements in an array
current()Returns the current element in an array
each()Deprecated from PHP 7.2. Returns the current key and value pair from an array
end()Sets the internal pointer of an array to its last element
extract()Imports variables into the current symbol table from an array
in_array()Checks if a specified value exists in an array
key()Fetches a key from an array
krsort()Sorts an associative array in descending order, according to the key
ksort()Sorts an associative array in ascending order, according to the key
list()Assigns variables as if they were an array
natcasesort()Sorts an array using a case insensitive "natural order" algorithm
natsort()Sorts an array using a "natural order" algorithm
next()Advance the internal array pointer of an array
pos()Alias of current()
prev()Rewinds the internal array pointer
range()Creates an array containing a range of elements
reset()Sets the internal pointer of an array to its first element
rsort()Sorts an indexed array in descending order
shuffle()Shuffles an array
sizeof()Alias of count()
sort()Sorts an indexed array in ascending order
uasort()Sorts an array by values using a user-defined comparison function
uksort()Sorts an array by keys using a user-defined comparison function
usort()Sorts an array using a user-defined comparison function
PHP Array Reference

Example

Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values: <?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> Try it Yourself »

Definition and Usage

The array() function is used to create an array. In PHP, there are three types of arrays:
  • Indexed arrays - Arrays with numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays
  • Syntax

    Syntax for indexed arrays: array(value1, value2, value3, etc.) Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.)

    Parameter Values

    ParameterDescription
    keySpecifies the key (numeric or string)
    valueSpecifies the value

    Technical Details

    Return Value: Returns an array of the parameters
    PHP Version: 4+
    Changelog: As of PHP 5.4, it is possible to use a short array syntax, which replaces array() with []. E.g. $cars=["Volvo","BMW"]; instead of $cars=array("Volvo","BMW");

    More Examples

    Example

    Create an associative array named $age: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?> Try it Yourself »

    Example

    Loop through and print all the values of an indexed array: <?php $cars=array("Volvo","BMW","Toyota"); $arrlength=count($cars);for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; }?> Try it Yourself »

    Example

    Loop through and print all the values of an associative array: <?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; }?> Try it Yourself »

    Example

    Create a multidimensional array: <?php// A two-dimensional array:$cars=array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) );?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Change all keys in an array to uppercase: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); print_r(array_change_key_case($age,CASE_UPPER));?> Try it Yourself »

    Definition and Usage

    The array_change_key_case() function changes all keys in an array to lowercase or uppercase.

    Syntax

    array_change_key_case(array, case)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use
    caseOptional. Possible values:
  • CASE_LOWER - Default value. Changes the keys to lowercase
  • CASE_UPPER - Changes the keys to uppercase
  • Technical Details

    Return Value: Returns an array with its keys in lowercase or uppercase, or FALSE if array is not an array
    PHP Version: 4.2+

    More Examples

    Example

    Change all keys in an array to lowercase: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); print_r(array_change_key_case($age,CASE_LOWER));?> Try it Yourself »

    Example

    If two or more keys will be equal after running array_change_key_case() (e.g. "b" and "B"), the latest array will override the other: <?php $pets=array("a"=>"Cat","B"=>"Dog","c"=>"Horse","b"=>"Bird"); print_r(array_change_key_case($pets,CASE_UPPER));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Split an array into chunks of two: <?php $cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel"); print_r(array_chunk($cars,2));?> Try it Yourself »

    Definition and Usage

    The array_chunk() function splits an array into chunks of new arrays.

    Syntax

    array_chunk(array, size, preserve_key)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use
    sizeRequired. An integer that specifies the size of each chunk
    preserve_keyOptional. Possible values:
  • true - Preserves the keys
  • false - Default. Reindexes the chunk numerically
  • Technical Details

    Return Value: Returns a multidimensional indexed array, starting with zero, with each dimension containing size elements
    PHP Version: 4.2+

    More Examples

    Example

    Split an array into chunks of two and preserve the original keys: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43","Harry"=>"50");print_r(array_chunk($age,2,true));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Get column of last names from a recordset: <?php// An array that represents a possible record set returned from a database$a = array( array( 'id' => 5698, 'first_name' => 'Peter', 'last_name' => 'Griffin', ), array( 'id' => 4767, 'first_name' => 'Ben', 'last_name' => 'Smith', ), array( 'id' => 3809, 'first_name' => 'Joe', 'last_name' => 'Doe', ));$last_names = array_column($a, 'last_name');print_r($last_names);?> Output: Array( [0] => Griffin [1] => Smith [2] => Doe)

    Definition and Usage

    The array_column() function returns the values from a single column in the input array.

    Syntax

    array_column(array, column_key, index_key)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the multi-dimensional array (record-set) to use. As of PHP 7.0, this can also be an array of objects.
    column_keyRequired. An integer key or a string key name of the column of values to return. This parameter can also be NULL to return complete arrays (useful together with index_key to re-index the array)
    index_keyOptional. The column to use as the index/keys for the returned array

    Technical Details

    Return Value: Returns an array of values that represents a single column from the input array
    PHP Version: 5.5+

    More Examples

    Example

    Get column of last names from a recordset, indexed by the "id" column: <?php// An array that represents a possible record set returned from a database$a = array( array( 'id' => 5698, 'first_name' => 'Peter', 'last_name' => 'Griffin', ), array( 'id' => 4767, 'first_name' => 'Ben', 'last_name' => 'Smith', ), array( 'id' => 3809, 'first_name' => 'Joe', 'last_name' => 'Doe', ));$last_names = array_column($a, 'last_name', 'id');print_r($last_names); ?> Output: Array( [5698] => Griffin [4767] => Smith [3809] => Doe) PHP Array Reference PHP Array Reference

    Example

    Create an array by using the elements from one "keys" array and one "values" array: <?php $fname=array("Peter","Ben","Joe");$age=array("35","37","43"); $c=array_combine($fname,$age);print_r($c);?> Try it Yourself »

    Definition and Usage

    The array_combine() function creates an array by using the elements from one "keys" array and one "values" array. Note: Both arrays must have equal number of elements!

    Syntax

    array_combine(keys, values)

    Parameter Values

    ParameterDescription
    keysRequired. Array of keys
    valuesRequired. Array of values

    Technical Details

    Return Value: Returns the combined array. FALSE if number of elements does not match
    PHP Version: 5+
    Changelog: Versions before PHP 5.4 issues E_WARNING and returns FALSE for empty arrays
    PHP Array Reference PHP Array Reference

    Example

    Count all the values of an array: <?php $a=array("A","Cat","Dog","A","Dog"); print_r(array_count_values($a));?> Try it Yourself »

    Definition and Usage

    The array_count_values() function counts all the values of an array.

    Syntax

    array_count_values(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying the array to count values of

    Technical Details

    Return Value: Returns an associative array, where the keys are the original array's values, and the values are the number of occurrences
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Compare the values of two arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue");$result=array_diff($a1,$a2);print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_diff(array1, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 4.0.1+

    More Examples

    Example

    Compare the values of three arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"black","g"=>"purple");$a3=array("a"=>"red","b"=>"black","h"=>"yellow"); $result=array_diff($a1,$a2,$a3);print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"red","b"=>"green","c"=>"blue");$result=array_diff_assoc($a1,$a2); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_diff_assoc() function compares the keys and values of two (or more) arrays, and returns the differences. This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_diff_assoc(array1,array2,array3...)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 4.3+

    More Examples

    Example

    Compare the keys and values of two arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff_assoc($a1,$a2);print_r($result);?> Try it Yourself »

    Example

    Compare the keys and values of three arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"red","f"=>"green","g"=>"blue");$a3=array("h"=>"red","b"=>"green","g"=>"blue"); $result=array_diff_assoc($a1,$a2,$a3);print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys of two arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","c"=>"blue","d"=>"pink"); $result=array_diff_key($a1,$a2);print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_diff_key() function compares the keys of two (or more) arrays, and returns the differences. This function compares the keys of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_diff_key(array1, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5.1+

    More Examples

    Example

    Compare the keys of two indexed arrays, and return the differences: <?php $a1=array("red","green","blue","yellow");$a2=array("red","green","blue"); $result=array_diff_key($a1,$a2);print_r($result);?> Try it Yourself »

    Example

    Compare the keys of three arrays, and return the differences: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("c"=>"yellow","d"=>"black","e"=>"brown"); $a3=array("f"=>"green","c"=>"purple","g"=>"red");$result=array_diff_key($a1,$a2,$a3); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays (use a user-defined function to compare the keys), and return the differences: <?phpfunction myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("d"=>"red","b"=>"green","e"=>"blue"); $result=array_diff_uassoc($a1,$a2,"myfunction");print_r($result); ?> Try it Yourself »

    Definition and Usage

    The array_diff_uassoc() function compares the keys and values of two (or more) arrays, and returns the differences. Note: This function uses a user-defined function to compare the keys! This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_diff_uassoc(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5+

    More Examples

    Example

    Compare the keys and values of three arrays (use a user-defined function to compare the keys), and return the differences: <?phpfunction myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","b"=>"green","d"=>"blue"); $a3=array("e"=>"yellow","a"=>"red","d"=>"blue");$result=array_diff_uassoc($a1,$a2,$a3,"myfunction"); print_r($result); ?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys of two arrays (using a user-defined key comparison function), and return the differences: <?phpfunction myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"blue","b"=>"black","e"=>"blue"); $result=array_diff_ukey($a1,$a2,"myfunction");print_r($result); ?> Try it Yourself »

    Definition and Usage

    The array_diff_ukey() function compares the keys of two (or more) arrays, and returns the differences. Note: This function uses a user-defined function to compare the keys! This function compares the keys of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_diff_ukey(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5.1+

    More Examples

    Example

    Compare the keys of three arrays (use a user-defined function to compare the keys), and return the differences: <?phpfunction myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"black","b"=>"yellow","d"=>"brown"); $a3=array("e"=>"purple","f"=>"white","a"=>"gold");$result=array_diff_ukey($a1,$a2,$a3,"myfunction"); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Fill an array with values: <?php $a1=array_fill(3,4,"blue");print_r($a1);?> Try it Yourself »

    Definition and Usage

    The array_fill() function fills an array with values.

    Syntax

    array_fill(index, number, value)

    Parameter Values

    ParameterDescription
    indexRequired. The first index of the returned array
    numberRequired. Specifies the number of elements to insert
    valueRequired. Specifies the value to use for filling the array

    Technical Details

    Return Value: Returns the filled array
    PHP Version: 4.2+
    PHP Array Reference PHP Array Reference

    Example

    Fill an array with values, specifying keys: <?php $keys=array("a","b","c","d");$a1=array_fill_keys($keys,"blue"); print_r($a1);?> Try it Yourself »

    Definition and Usage

    The array_fill_keys() function fills an array with values, specifying keys.

    Syntax

    array_fill_keys(keys, value)

    Parameter Values

    ParameterDescription
    keysRequired. Array of values that will be used as keys
    valueRequired. Specifies the value to use for filling the array

    Technical Details

    Return Value: Returns the filled array
    PHP Version: 5.2+
    PHP Array Reference PHP Array Reference

    Example

    Filter the values of an array using a callback function: <?phpfunction test_odd($var) { return($var & 1); }$a1=array(1,3,2,3,4);print_r(array_filter($a1,"test_odd"));?> Try it Yourself »

    Definition and Usage

    The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

    Syntax

    array_filter(array, callbackfunction, flag)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to filter
    callbackfunctionOptional. Specifies the callback function to use
    flagOptional. Specifies what arguments are sent to callback:
  • ARRAY_FILTER_USE_KEY - pass key as the only argument to callback (instead of the value)
  • ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback (instead of the value)
  • Technical Details

    Return Value: Returns the filtered array
    PHP Version: 4.0.6+
    PHP Changelog: PHP 5.6: Added optional flag parameter
    PHP Array Reference PHP Array Reference

    Example

    Flip all keys with their associated values in an array: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $result=array_flip($a1);print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_flip() function flips/exchanges all keys with their associated values in an array.

    Syntax

    array_flip(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array of key/value pairs to be flipped

    Technical Details

    Return Value: Returns the flipped array on success. NULL on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Compare the values of two arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue");$result=array_intersect($a1,$a2);print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_intersect(array1, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 4.0.1+

    More Examples

    Example

    Compare the values of three arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"black","g"=>"purple");$a3=array("a"=>"red","b"=>"black","h"=>"yellow"); $result=array_intersect($a1,$a2,$a3);print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"red","b"=>"green","c"=>"blue");$result=array_intersect_assoc($a1,$a2); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_intersect_assoc() function compares the keys and values of two (or more) arrays, and returns the matches. This function compares the keys and values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_intersect_assoc(array1,array2,array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. The first array is the array that the others will be compared with
    array2Required. An array to be compared with the first array
    array3,...Optional. An array to be compared with the first array

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 4.3.0+

    More Examples

    Example

    Compare the keys and values of three arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"red","b"=>"green","g"=>"blue");$a3=array("a"=>"red","b"=>"green","g"=>"blue"); $result=array_intersect_assoc($a1,$a2,$a3);print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys of two arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","c"=>"blue","d"=>"pink"); $result=array_intersect_key($a1,$a2);print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_intersect_key() function compares the keys of two (or more) arrays, and returns the matches. This function compares the keys of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_intersect_key(array1, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. The first array is the array that the others will be compared with
    array2Required. An array to be compared with the first array
    array3,...Optional. An array to be compared with the first array

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5.1.0+

    More Examples

    Example

    Compare the keys of two indexed arrays, and return the matches: <?php $a1=array("red","green","blue","yellow");$a2=array("red","green","blue"); $result=array_intersect_key($a1,$a2);print_r($result);?> Try it Yourself »

    Example

    Compare the keys of three arrays, and return the matches: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("c"=>"yellow","d"=>"black","e"=>"brown"); $a3=array("f"=>"green","c"=>"purple","g"=>"red");$result=array_intersect_key($a1,$a2,$a3); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays, and return the matches (using a user-defined key comparison function): <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("d"=>"red","b"=>"green","e"=>"blue"); $result=array_intersect_uassoc($a1,$a2,"myfunction");print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_intersect_uassoc() function compares the keys and values of two (or more) arrays, and returns the matches. Note: This function uses a user-defined function to compare the keys! This function compares the keys and values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_intersect_uassoc(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The first array is the array that the others will be compared with
    array2Required. An array to be compared with the first array
    array3,...Optional. An array to be compared with the first array
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5+

    More Examples

    Example

    Compare the keys and values of three arrays (use a user-defined function to compare the keys), and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","b"=>"green","d"=>"blue"); $a3=array("e"=>"yellow","a"=>"red","d"=>"blue");$result=array_intersect_uassoc($a1,$a2,$a3,"myfunction"); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys of two arrays (using a user-defined key comparison function), and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"blue","b"=>"black","e"=>"blue"); $result=array_intersect_ukey($a1,$a2,"myfunction");print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_intersect_ukey() function compares the keys of two (or more) arrays, and returns the matches. Note: This function uses a user-defined function to compare the keys! This function compares the keys of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_intersect_ukey(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The first array is the array that the others will be compared with
    array2Required. An array to be compared with the first array
    array3,...Optional. An array to be compared with the first array
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5.1.0+

    More Examples

    Example

    Compare the keys of three arrays (use a user-defined function to compare the keys), and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"black","b"=>"yellow","d"=>"brown"); $a3=array("e"=>"purple","f"=>"white","a"=>"gold");$result=array_intersect_ukey($a1,$a2,$a3,"myfunction"); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Check if the key "Volvo" exists in an array: <?php $a=array("Volvo"=>"XC90","BMW"=>"X5");if (array_key_exists("Volvo",$a)) { echo "Key exists!"; }else { echo "Key does not exist!"; }?> Try it Yourself »

    Definition and Usage

    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. Tip: Remember that if you skip the key when you specify an array, an integer key is generated, starting at 0 and increases by 1 for each value. (See example below)

    Syntax

    array_key_exists(key, array)

    Parameter Values

    ParameterDescription
    keyRequired. Specifies the key
    arrayRequired. Specifies an array

    Technical Details

    Return Value: Returns TRUE if the key exists and FALSE if the key does not exist
    PHP Version: 4.0.7+

    More Examples

    Example

    Check if the key "Toyota" exists in an array: <?php $a=array("Volvo"=>"XC90","BMW"=>"X5");if (array_key_exists("Toyota",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?> Try it Yourself »

    Example

    Check if the integer key "0" exists in an array: <?php $a=array("Volvo","BMW"); if (array_key_exists(0,$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return an array containing the keys: <?php $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");print_r(array_keys($a)); ?> Try it Yourself »

    Definition and Usage

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

    Syntax

    array_keys(array, value, strict)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    valueOptional. You can specify a value, then only the keys with this value are returned
    strictOptional. Used with the value parameter. Possible values:
  • true - Returns the keys with the specified value, depending on type: the number 5 is not the same as the string "5".
  • false - Default value. Not depending on type, the number 5 is the same as the string "5".
  • Technical Details

    Return Value: Returns an array containing the keys
    PHP Version: 4+
    Changelog: The strict parameter was added in PHP 5.0

    More Examples

    Example

    Using the value parameter: <?php $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");print_r(array_keys($a,"Highlander"));?> Try it Yourself »

    Example

    Using the strict parameter, false: <?php $a=array(10,20,30,"10");print_r(array_keys($a,"10",false));?> Try it Yourself »

    Example

    Using the strict parameter, true: <?php$a=array(10,20,30,"10");print_r(array_keys($a,"10",true));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Send each value of an array to a function, multiply each value by itself, and return an array with the new values: <?php function myfunction($v){ return($v*$v);} $a=array(1,2,3,4,5);print_r(array_map("myfunction",$a)); ?> Try it Yourself »

    Definition and Usage

    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. Tip: You can assign one array to the function, or as many as you like.

    Syntax

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

    Parameter Values

    ParameterDescription
    myfunctionRequired. The name of the user-made function, or null
    array1Required. Specifies an array
    array2Optional. Specifies an array
    array3Optional. Specifies an array

    Technical Details

    Return Value: Returns an array containing the values of array1, after applying the user-made function to each one
    PHP Version: 4.0.6+

    More Examples

    Example

    Using a user-made function to change the values of an array: <?php function myfunction($v){if ($v==="Dog") { return "Fido"; }return $v;}$a=array("Horse","Dog","Cat"); print_r(array_map("myfunction",$a));?> Try it Yourself »

    Example

    Using two arrays: <?php function myfunction($v1,$v2){if ($v1===$v2) { return "same"; }return "different";}$a1=array("Horse","Dog","Cat"); $a2=array("Cow","Dog","Rat");print_r(array_map("myfunction",$a1,$a2));?> Try it Yourself »

    Example

    Change all letters of the array values to uppercase: <?php function myfunction($v) {$v=strtoupper($v); return $v; }$a=array("Animal" => "horse", "Type" => "mammal");print_r(array_map("myfunction",$a));?> Try it Yourself »

    Example

    Assign null as the function name: <?php$a1=array("Dog","Cat"); $a2=array("Puppy","Kitten"); print_r(array_map(null,$a1,$a2));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Merge two arrays into one array: <?php $a1=array("red","green");$a2=array("blue","yellow");print_r(array_merge($a1,$a2)); ?> Try it Yourself »

    Definition and Usage

    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. Note: If two or more array elements have the same key, the last one overrides the others. Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value (See example below). Tip: The difference between this function and the array_merge_recursive() 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(array1, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. Specifies an array
    array2Optional. Specifies an array
    array3,...Optional. Specifies an array

    Technical Details

    Return Value: Returns the merged array
    PHP Version: 4+
    Changelog: As of PHP 5.0, this function only accept parameters of type array

    More Examples

    Example

    Merge two associative arrays into one array: <?php $a1=array("a"=>"red","b"=>"green"); $a2=array("c"=>"blue","b"=>"yellow"); print_r(array_merge($a1,$a2));?> Try it Yourself »

    Example

    Using only one array parameter with integer keys: <?php $a=array(3=>"red",4=>"green"); print_r(array_merge($a));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Merge two arrays into one array: <?php $a1=array("a"=>"red","b"=>"green"); $a2=array("c"=>"blue","b"=>"yellow"); print_r(array_merge_recursive($a1,$a2)); ?> Try it Yourself »

    Definition and Usage

    The array_merge_recursive() function merges one or 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. Note: If you assign only one array to the array_merge_recursive() function, it will behave exactly the same as the array_merge() function.

    Syntax

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

    Parameter Values

    ParameterDescription
    array1Required. Specifies an array
    array2Optional. Specifies an array
    array3,...Optional. Specifies an array

    Technical Details

    Return Value: Returns the merged array
    PHP Version: 4.0.1+
    PHP Array Reference PHP Array Reference

    Example

    Return a sorted array in ascending order: <?php $a=array("Dog","Cat","Horse","Bear","Zebra"); array_multisort($a); print_r($a); ?> Try it Yourself »

    Definition and Usage

    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. Note: You can assign the sortorder and the sorttype parameters after each array. If not specified, each array parameter uses the default values.

    Syntax

    array_multisort(array1, sortorder, sorttype, array2, array3, ...)

    Parameter Values

    ParameterDescription
    array1Required. Specifies an array
    sortorderOptional. Specifies the sorting order. Possible values:
  • SORT_ASC - Default. Sort in ascending order (A-Z)
  • SORT_DESC - Sort in descending order (Z-A)
  • sorttypeOptional. Specifies the type to use, when comparing elements. Possible values:
  • SORT_REGULAR - Default. Compare elements normally (Standard ASCII)
  • SORT_NUMERIC - Compare elements as numeric values
  • SORT_STRING - Compare elements as string values
  • SORT_LOCALE_STRING - Compare elements as string, based on the current locale (can be changed using setlocale())
  • SORT_NATURAL - Compare elements as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively
  • array2Optional. Specifies an array
    array3Optional. Specifies an array

    Technical Details

    Return Value: Returns TRUE on success or FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 5.4: Added sorting type SORT_NATURAL and SORT_FLAG_CASE PHP 5.3: Added sorting type SORT_LOCALE_STRING

    More Examples

    Example

    Return a sorted array in ascending order: <?php $a1=array("Dog","Cat"); $a2=array("Fido","Missy"); array_multisort($a1,$a2); print_r($a1); print_r($a2);?> Try it Yourself »

    Example

    See how it sorts when two values are the same: <?php $a1=array("Dog","Dog","Cat"); $a2=array("Pluto","Fido","Missy"); array_multisort($a1,$a2); print_r($a1); print_r($a2);?> Try it Yourself »

    Example

    Using sorting parameters: <?php$a1=array("Dog","Dog","Cat");$a2=array("Pluto","Fido","Missy");array_multisort($a1,SORT_ASC,$a2,SORT_DESC);print_r($a1);print_r($a2);?> Try it Yourself »

    Example

    Merge two arrays and sort them as numbers, in descending order: <?php $a1=array(1,30,15,7,25);$a2=array(4,30,20,41,66);$num=array_merge($a1,$a2); array_multisort($num,SORT_DESC,SORT_NUMERIC);print_r($num);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return 5 elements and insert a value of "blue" to the new elements in the array: <?php $a=array("red","green"); print_r(array_pad($a,5,"blue")); ?> Try it Yourself »

    Definition and Usage

    The array_pad() function inserts a specified number of elements, with a specified value, to an array. Tip: If you assign a negative size parameter, the function will insert new elements BEFORE the original elements (See example below). Note: This function will not delete any elements if the size parameter is less than the size of the original array.

    Syntax

    array_pad(array, size, value)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    sizeRequired. Specifies the number of elements in the array returned from the function
    valueRequired. Specifies the value of the new elements in the array returned from the function

    Technical Details

    Return Value: Returns an array with new elements
    PHP Version: 4+

    More Examples

    Example

    Using a negative size parameter: <?php $a=array("red","green"); print_r(array_pad($a,-5,"blue"));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Delete the last element of an array: <?php $a=array("red","green","blue"); array_pop($a); print_r($a); ?> Try it Yourself »

    Definition and Usage

    The array_pop() function deletes the last element of an array.

    Syntax

    array_pop(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array

    Technical Details

    Return Value: Returns the last value of array. If array is empty, or is not an array, NULL will be returned.
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Calculate and return the product of an array: <?php $a=array(5,5); echo(array_product($a)); ?> Try it Yourself »

    Definition and Usage

    The array_product() function calculates and returns the product of an array.

    Syntax

    array_product(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array

    Technical Details

    Return Value: Returns the product as an integer or float
    PHP Version: 5.1.0+
    Changelog: As of PHP 5.3.6, the product of an empty array is 1. Before PHP 5.3.6, this function would return 0 for an empty array.

    More Examples

    Example

    Calculate and return the product of an array: <?php $a=array(5,5,2,10); echo(array_product($a));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Insert "blue" and "yellow" to the end of an array: <?php $a=array("red","green"); array_push($a,"blue","yellow"); print_r($a);?> Try it Yourself »

    Definition and Usage

    The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

    Syntax

    array_push(array, value1, value2, ...)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    value1Optional. Specifies the value to add (Required in PHP versions before 7.3)
    value2Optional. Specifies the value to add

    Technical Details

    Return Value: Returns the new number of elements in the array
    PHP Version: 4+
    Change log: As of version 7.3 this function can be called with only the array parameter

    More Examples

    Example

    An array with string keys: <?php $a=array("a"=>"red","b"=>"green"); array_push($a,"blue","yellow"); print_r($a);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return an array of random keys: <?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]];?> Try it Yourself »

    Definition and Usage

    The array_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)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    numberOptional. Specifies how many random keys to return

    Technical Details

    Return Value: Returns a random key from an array, or an array of random keys if you specify that the function should return more than one key
    PHP Version: 4+
    PHP Changelog: PHP 7.1: rand() uses the Mersenne Twister random number generator PHP 5.2.1: The resulting array of keys is no longer shuffled PHP 4.2: The random number generator is seeded automatically

    More Examples

    Example

    Return a random key from an array: <?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1));?> Try it Yourself »

    Example

    Return an array of random string keys: <?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,2));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Send the values in an array to a user-defined function and return a string: <?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction")); ?> Try it Yourself »

    Definition and Usage

    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)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    myfunctionRequired. Specifies the name of the function
    initialOptional. Specifies the initial value to send to the function

    Technical Details

    Return Value: Returns the resulting value
    PHP Version: 4.0.5+
    PHP Changelog: As of PHP 5.3.0, the initial parameter accepts multiple types (mixed). Versions prior to PHP 5.3.0, only allowed integer.

    More Examples

    Example

    With the initial parameter: <?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction",5));?> Try it Yourself »

    Example

    Returning a sum: <?php function myfunction($v1,$v2) { return $v1+$v2; } $a=array(10,15,20); print_r(array_reduce($a,"myfunction",5));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Replace the values of the first array ($a1) with the values from the second array ($a2): <?php $a1=array("red","green");$a2=array("blue","yellow"); print_r(array_replace($a1,$a2)); ?> Try it Yourself »

    Definition and Usage

    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). If a key exist in array2 and not in array1, it will be created in array1 (See Example 2 below). If multiple arrays are used, values from later arrays will overwrite the previous ones (See Example 3 below). Tip: Use array_replace_recursive() to replace the values of array1 with the values from following arrays recursively.

    Syntax

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

    Parameter Values

    ParameterDescription
    array1Required. Specifies an array
    array2Optional. Specifies an array which will replace the values of array1
    array3,...Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones.

    Technical Details

    Return Value: Returns the replaced array, or NULL if an error occurs
    PHP Version: 5.3.0+

    More Examples

    Example 1

    If a key from array1 exists in array2, and if the key only exists in array1: <?php $a1=array("a"=>"red","b"=>"green");$a2=array("a"=>"orange","burgundy"); print_r(array_replace($a1,$a2));?> Try it Yourself »

    Example 2

    If a key exists in array2 and not in array1: <?php $a1=array("a"=>"red","green");$a2=array("a"=>"orange","b"=>"burgundy"); print_r(array_replace($a1,$a2));?> Try it Yourself »

    Example 3

    Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2): <?php $a1=array("red","green");$a2=array("blue","yellow");$a3=array("orange","burgundy"); print_r(array_replace($a1,$a2,$a3));?> Try it Yourself »

    Example 4

    Using numeric keys - If a key exists in array2 and not in array1: <?php $a1=array("red","green","blue","yellow"); $a2=array(0=>"orange",3=>"burgundy");print_r(array_replace($a1,$a2));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Replace the values of the first array with the values from the second array recursively: <?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)); ?> Try it Yourself »

    Definition and Usage

    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. 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. If a key exist in array2 and not in array1, it will be created in array1. If multiple arrays are used, values from later arrays will overwrite the previous ones. Note: If you do not specify a key for each array, this function will behave exactly the same as the array_replace() function.

    Syntax

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

    Parameter Values

    ParameterDescription
    array1Required. Specifies an array
    array2Optional. Specifies an array which will replace the values of array1
    array3,...Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones.

    Technical Details

    Return Value: Returns the replaced array, or NULL if an error occurs
    PHP Version: 5.3.0+

    More Examples

    Example

    Multiple arrays: <?php $a1=array("a"=>array("red"),"b"=>array("green","blue")); $a2=array("a"=>array("yellow"),"b"=>array("black")); $a3=array("a"=>array("orange"),"b"=>array("burgundy"));print_r(array_replace_recursive($a1,$a2,$a3));?> Try it Yourself »

    Example

    Differences between array_replace() and array_replace_recursive(): <?php $a1=array("a"=>array("red"),"b"=>array("green","blue"),); $a2=array("a"=>array("yellow"),"b"=>array("black"));$result=array_replace_recursive($a1,$a2); print_r($result);$result=array_replace($a1,$a2);print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return an array in the reverse order: <?php $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a)); ?> Try it Yourself »

    Definition and Usage

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

    Syntax

    array_reverse(array, preserve)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    preserveOptional. Specifies if the function should preserve the keys of the array or not. Possible values:
  • true
  • false
  • Technical Details

    Return Value: Returns the reversed array
    PHP Version: 4+
    PHP Changelog: The preserve parameter was added in PHP 4.0.3

    More Examples

    Example

    Return the original array, the reversed array and the preserved array: <?php $a=array("Volvo","XC90",array("BMW","Toyota"));$reverse=array_reverse($a); $preserve=array_reverse($a,true);print_r($a);print_r($reverse); print_r($preserve);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Search an array for the value "red" and return its key: <?php $a=array("a"=>"red","b"=>"green","c"=>"blue");echo array_search("red",$a); ?> Try it Yourself »

    Definition and Usage

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

    Syntax

    array_search(value, array, strict)

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to search for
    arrayRequired. Specifies the array to search in
    strictOptional. If this parameter is set to TRUE, then this function will search for identical elements in the array. Possible values:
  • true
  • false - Default
  • When set to true, the number 5 is not the same as the string 5 (See example 2)

    Technical Details

    Return Value: Returns the key of a value if it is found in the array, and FALSE otherwise. If the value is found in the array more than once, the first matching key is returned.
    PHP Version: 4.0.5+
    PHP Changelog: This function returns NULL if invalid parameters are passed to it (this applies to all PHP functions as of 5.3.0).As of PHP 4.2.0, this function returns FALSE on failure instead of NULL.

    More Examples

    Example

    Search an array for the value 5 and return its key (notice the "): <?php $a=array("a"=>"5","b"=>5,"c"=>"5"); echo array_search(5,$a,true);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Remove the first element (red) from an array, and return the value of the removed element: <?php $a=array("a"=>"red","b"=>"green","c"=>"blue");echo array_shift($a); print_r ($a); ?> Try it Yourself »

    Definition and Usage

    The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

    Syntax

    array_shift(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array

    Technical Details

    Return Value: Returns the value of the removed element from an array, or NULL if the array is empty
    PHP Version: 4+

    More Examples

    Example

    Using numeric keys: <?php $a=array(0=>"red",1=>"green",2=>"blue"); echo array_shift($a); print_r ($a);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Start the slice from the third array element, and return the rest of the elements in the array: <?php $a=array("red","green","blue","yellow","brown");print_r(array_slice($a,2)); ?> Try it Yourself »

    Definition and Usage

    The array_slice() function returns selected parts of an array. Note: If the array have string keys, the returned array will always preserve the keys (See example 4).

    Syntax

    array_slice(array, start, length, preserve)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    startRequired. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
    lengthOptional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
    preserveOptional. Specifies if the function should preserve or reset the keys. Possible values:
  • true - Preserve keys
  • false - Default. Reset keys
  • Technical Details

    Return Value: Returns selected parts of an array
    PHP Version: 4+
    PHP Changelog: The preserve parameter was added in PHP 5.0.2

    More Examples

    Example 1

    Start the slice from from the second array element, and return only two elements: <?php $a=array("red","green","blue","yellow","brown");print_r(array_slice($a,1,2));?> Try it Yourself »

    Example 2

    Using a negative start parameter: <?php $a=array("red","green","blue","yellow","brown");print_r(array_slice($a,-2,1));?> Try it Yourself »

    Example 3

    With the preserve parameter set to true: <?php$a=array("red","green","blue","yellow","brown");print_r(array_slice($a,1,2,true));?> Try it Yourself »

    Example 4

    With both string and integer keys: <?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown"); print_r(array_slice($a,1,2)); $a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown"); print_r(array_slice($a,1,2));?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Remove elements from an array and replace it with new elements: <?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); ?> Try it Yourself »

    Definition and Usage

    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. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2). Note: The keys in the replaced array are not preserved.

    Syntax

    array_splice(array, start, length, array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array
    startRequired. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array.
    lengthOptional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will remove all elements, starting from the position set by the start-parameter.
    arrayOptional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array.

    Technical Details

    Return Value: Returns the array consisting of the extracted elements
    PHP Version: 4+

    More Examples

    Example 1

    The same example as the example on top of the page, but the output is the returned array: <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange");print_r(array_splice($a1,0,2,$a2));?> Try it Yourself »

    Example 2

    With the length parameter set to 0: <?php $a1=array("0"=>"red","1"=>"green"); $a2=array("0"=>"purple","1"=>"orange");array_splice($a1,1,0,$a2); print_r($a1);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return the sum of all the values in the array (5+15+25): <?php $a=array(5,15,25); echo array_sum($a); ?> Try it Yourself »

    Definition and Usage

    The array_sum() function returns the sum of all the values in the array.

    Syntax

    array_sum(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies an array

    Technical Details

    Return Value: Returns the sum of all the values in an array
    PHP Version: 4.0.4+
    PHP Changelog: PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which often converted them to zero, depending on their value)

    More Examples

    Example

    Return the sum of all the values in the array (52.2+13.7+0.9): <?php $a=array("a"=>52.2,"b"=>13.7,"c"=>0.9);echo array_sum($a);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the values of two arrays (use a user-defined function to compare the values) and return the differences: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue"); $a2=array("a"=>"blue","b"=>"black","e"=>"blue");$result=array_udiff($a1,$a2,"myfunction"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_udiff() function compares the values of two or more arrays, and returns the differences. Note: This function uses a user-defined function to compare the values! This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_udiff(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5.1.0+

    More Examples

    Example

    Compare the values of three arrays (use a user-defined function to compare the values), and return the differences: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue","yellow"); $a2=array("A"=>"red","b"=>"GREEN","yellow","black");$a3=array("a"=>"green","b"=>"red","yellow","black"); $result=array_udiff($a1,$a2,$a3,"myfunction");print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays (using a built-in function to compare the keys and a user-defined function to compare the values) and return the differences: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue"); $a2=array("a"=>"red","b"=>"blue","c"=>"green");$result=array_udiff_assoc($a1,$a2,"myfunction"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_udiff() function compares the keys and values of two or more arrays, and returns the differences. Note: This function uses a built-in function to compare the keys, and a user-defined function to compare the values! This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

    Syntax

    array_udiff_assoc(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5+
    PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays (using two user-defined functions for comparison) and return the differences: <?php function myfunction_key($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}function myfunction_value($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","b"=>"green","c"=>"green"); $result=array_udiff_uassoc($a1,$a2,"myfunction_key","myfunction_value"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_udiff_uassoc() function compares the keys and values of two or more arrays, and returns the differences. Note: This function uses two user-defined functions for comparison; the key is used in the first function and the value is used in the second! This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2or array3, etc.

    Syntax

    array_udiff_uassoc(array1, array2, array3, ..., myfunc_key, myfunc_value)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunc_keyRequired. The name of the user-defined function that compares the array keys.A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument
    myfunc_valueRequired. The name of the user-defined function that compares the array values.A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are not present in any of the other arrays
    PHP Version: 5+
    PHP Array Reference PHP Array Reference

    Example

    Compare the values of two arrays (use a user-defined function to compare the values) and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue"); $a2=array("a"=>"blue","b"=>"black","e"=>"blue");$result=array_uintersect($a1,$a2,"myfunction"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_uintersect() function compares the values of two or more arrays, and returns the matches. Note: This function uses a user-defined function to compare the values! This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_uintersect(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5+

    More Examples

    Example

    Compare the values of three arrays (use a user-defined function to compare the values), and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue","yellow"); $a2=array("A"=>"red","b"=>"GREEN","yellow","black");$a3=array("a"=>"green","b"=>"red","yellow","black"); $result=array_uintersect($a1,$a2,$a3,"myfunction");print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays (using a built-in function to compare the keys and a user-defined function to compare the values) and return the matches: <?php function myfunction($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}$a1=array("a"=>"red","b"=>"green","c"=>"blue"); $a2=array("a"=>"red","b"=>"blue","c"=>"green");$result=array_uintersect_assoc($a1,$a2,"myfunction"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_uintersect_assoc() function compares the keys and values of two or more arrays, and returns the matches. Note: This function uses a built-in function to compare the keys, and a user-defined function to compare the values! This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_uintersect_assoc(array1, array2, array3, ..., myfunction)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunctionRequired. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5+
    PHP Array Reference PHP Array Reference

    Example

    Compare the keys and values of two arrays (using two user-defined functions for comparison) and return the matches: <?php function myfunction_key($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;}function myfunction_value($a,$b){if ($a===$b) { return 0; } return ($a>$b)?1:-1;} $a1=array("a"=>"red","b"=>"green","c"=>"blue");$a2=array("a"=>"red","b"=>"green","c"=>"green"); $result=array_uintersect_uassoc($a1,$a2,"myfunction_key","myfunction_value"); print_r($result);?> Try it Yourself »

    Definition and Usage

    The array_uintersect_uassoc() function compares the keys and values of two or more arrays, and returns the matches. Note: This function uses two user-defined functions for comparison; the key is used in the first function and the value is used in the second! This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

    Syntax

    array_uintersect_uassoc(array1, array2, array3, ..., myfunc_key, myfunc_value)

    Parameter Values

    ParameterDescription
    array1Required. The array to compare from
    array2Required. An array to compare against
    array3,...Optional. More arrays to compare against
    myfunc_keyRequired. The name of the user-defined function that compares the array keys.A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument
    myfunc_valueRequired. The name of the user-defined function that compares the array values.A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.

    Technical Details

    Return Value: Returns an array containing the entries from array1 that are present in all of the other arrays
    PHP Version: 5+
    PHP Array Reference PHP Array Reference

    Example

    Remove duplicate values from an array: <?php $a=array("a"=>"red","b"=>"green","c"=>"red");print_r(array_unique($a)); ?> Try it Yourself »

    Definition and Usage

    The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

    Syntax

    array_unique(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying an array
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • SORT_STRING - Default. Compare items as strings
  • SORT_REGULAR - Compare items normally (don't change types)
  • SORT_NUMERIC - Compare items numerically
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • Technical Details

    Return Value: Returns the filtered array
    PHP Version: 4.0.1+
    PHP Changelog: PHP 7.2: If sorttype is SORT_STRING, this returns a new array and adds the unique elements. PHP 5.2.9: The default value of sorttype was changed to SORT_REGULAR. PHP 5.2.1: The default value of sorttype was changed back to SORT_STRING.
    PHP Array Reference PHP Array Reference

    Example

    Insert the element "blue" to an array: <?php $a=array("a"=>"red","b"=>"green");array_unshift($a,"blue");print_r($a); ?> Try it Yourself »

    Definition and Usage

    The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like. Note: Numeric keys will start at 0 and increase by 1. String keys will remain the same.

    Syntax

    array_unshift(array, value1, value2, value3, ...)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying an array
    value1Optional. Specifies a value to insert (Required in PHP versions before 7.3)
    value2Optional. Specifies a value to insert
    value3Optional. Specifies a value to insert

    Technical Details

    Return Value: Returns the new number of elements in the array
    PHP Version: 4+
    PHP Changelog: PHP 7.3: This function can now be called with only the array parameter

    More Examples

    Example

    Show the return value: <?php $a=array("a"=>"red","b"=>"green");print_r(array_unshift($a,"blue"));?> Try it Yourself »

    Example

    Using numeric keys: <?php $a=array(0=>"red",1=>"green");array_unshift($a,"blue");print_r($a);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return all the values of an array (not the keys): <?php $a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");print_r(array_values($a)); ?> Try it Yourself »

    Definition and Usage

    The array_values() function returns an array containing all the values of an array. Tip: The returned array will have numeric keys, starting at 0 and increase by 1.

    Syntax

    array_values(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying an array

    Technical Details

    Return Value: Returns an array containing all the values of an array
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Run each array element in a user-defined function: <?php function myfunction($value,$key) { echo "The key $key has the value $value<br>"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction"); ?> Try it Yourself »

    Definition and Usage

    The array_walk() function runs each array element in a user-defined function. The array's keys and values are parameters in the function. Note: You can change an array element's value in the user-defined function by specifying the first parameter as a reference: &$value (See Example 2). Tip: To work with deeper arrays (an array inside an array), use the array_walk_recursive() function.

    Syntax

    array_walk(array, myfunction, parameter...)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying an array
    myfunctionRequired. The name of the user-defined function
    parameter,...Optional. Specifies a parameter to the user-defined function. You can assign one parameter to the function, or as many as you like

    Technical Details

    Return Value: Returns TRUE on success or FALSE on failure
    PHP Version: 4+

    More Examples

    Example 1

    With a parameter: <?php function myfunction($value,$key,$p) { echo "$key $p $value<br>"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction","has the value");?> Try it Yourself »

    Example 2

    Change an array element's value. (Notice the &$value) <?php function myfunction(&$value,$key) { $value="yellow"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction"); print_r($a);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Run each array element in a user-defined function: <?php function myfunction($value,$key){echo "The key $key has the value $value<br>";}$a1=array("a"=>"red","b"=>"green"); $a2=array($a1,"1"=>"blue","2"=>"yellow");array_walk_recursive($a2,"myfunction"); ?> Try it Yourself »

    Definition and Usage

    The array_walk_recursive() function runs each array element in a user-defined function. The array's keys and values are parameters in the function. The difference between this function and the array_walk() function is that with this function you can work with deeper arrays (an array inside an array).

    Syntax

    array_walk_recursive(array, myfunction, parameter...)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifying an array
    myfunctionRequired. The name of the user-defined function
    parameter,...Optional. Specifies a parameter to the user-defined function. You can assign one parameter to the function, or as many as you like.

    Technical Details

    Return Value: Returns TRUE on success or FALSE on failure
    PHP Version: 5+
    PHP Array Reference PHP Array Reference

    Example

    Sort an associative array in descending order, according to the value: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");arsort($age);?> Try it Yourself »

    Definition and Usage

    The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

    Syntax

    arsort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort an associative array in ascending order, according to the value: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");asort($age);?> Try it Yourself »

    Definition and Usage

    The asort() function sorts an associative array in ascending order, according to the value. Tip: Use the arsort() function to sort an associative array in descending order, according to the value. Tip: Use the ksort() function to sort an associative array in ascending order, according to the key.

    Syntax

    asort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Create an array from variables and their values: <?php $firstname = "Peter"; $lastname = "Griffin"; $age = "41"; $result = compact("firstname", "lastname", "age"); print_r($result); ?> Try it Yourself »

    Definition and Usage

    The compact() function creates an array from variables and their values. Note: Any strings that does not match variable names will be skipped.

    Syntax

    compact(var1, var2...)

    Parameter Values

    ParameterDescription
    var1Required. Can be a string with the variable name, or an array of variables
    var2,...Optional. Can be a string with the variable name, or an array of variables. Multiple parameters are allowed.

    Technical Details

    Return Value: Returns an array with all the variables added to it
    PHP Version: 4+
    Change log: As of version 7.3 this function issues an E_NOTICE level error if an unset variable is given

    More Examples

    Example

    Using a string that does not match a variable, and an array of variable names: <?php $firstname = "Peter"; $lastname = "Griffin"; $age = "41"; $name = array("firstname", "lastname"); $result = compact($name, "location", "age"); print_r($result);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return the number of elements in an array: <?php $cars=array("Volvo","BMW","Toyota");echo count($cars);?> Try it Yourself »

    Definition and Usage

    The count() function returns the number of elements in an array.

    Syntax

    count(array, mode)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array
    modeOptional. Specifies the mode. Possible values:
  • 0 - Default. Does not count all elements of multidimensional arrays
  • 1 - Counts the array recursively (counts all the elements of multidimensional arrays)
  • Technical Details

    Return Value: Returns the number of elements in the array
    PHP Version: 4+
    PHP Changelog: The mode parameter was added in PHP 4.2

    More Examples

    Example

    Count the array recursively: <?php $cars=array ( "Volvo"=>array ( "XC60", "XC90" ), "BMW"=>array ( "X3", "X5" ), "Toyota"=>array ( "Highlander" ) ); echo "Normal count: " . count($cars)."<br>";echo "Recursive count: " . count($cars,1);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Output the value of the current element in an array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The current() function returns the value of the current element in an array. Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. Tip: This function does not move the arrays internal pointer. Related methods:
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • reset() - moves the internal pointer to the first element of the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    current(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the current element in an array, or FALSE on empty elements or elements with no value
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return the current element key and value, and move the internal pointer forward: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); print_r (each($people)); ?> Try it Yourself »

    Definition and Usage

    The each() function returns the current element key and value, and moves the internal pointer forward. Note: The each() function is deprecated in PHP 7.2. This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key. Related methods:
  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • reset() - moves the internal pointer to the first element of the array
  • Syntax

    each(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the current element key and value. This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key. This function returns FALSE if there are no more array elements
    PHP Version: 4+
    PHP Changelog: This functions has been deprecated as of PHP 7.2

    More Examples

    Example

    Same example as the one on top of the page, but with a loop to output the whole array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); reset($people);while (list($key, $val) = each($people)) { echo "$key => $val<br>"; }?> Try it Yourself »

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Output the value of the current and the last element in an array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; echo end($people); ?> Try it Yourself »

    Definition and Usage

    The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods:
  • current() - returns the value of the current element in an array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • reset() - moves the internal pointer to the first element of the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    end(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the last element in the array on success, or FALSE if the array is empty
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Assign the values "Cat", "Dog" and "Horse" to the variables $a, $b and $c: <?php $a = "Original"; $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse"); extract($my_array); echo "\$a = $a; \$b = $b; \$c = $c"; ?> Try it Yourself »

    Definition and Usage

    The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

    Syntax

    extract(array, extract_rules, prefix)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use
    extract_rulesOptional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names are treated.Possible values:
  • EXTR_OVERWRITE - Default. On collision, the existing variable is overwritten
  • EXTR_SKIP - On collision, the existing variable is not overwritten
  • EXTR_PREFIX_SAME - On collision, the variable name will be given a prefix
  • EXTR_PREFIX_ALL - All variable names will be given a prefix
  • EXTR_PREFIX_INVALID - Only invalid or numeric variable names will be given a prefix
  • EXTR_IF_EXISTS - Only overwrite existing variables in the current symbol table, otherwise do nothing
  • EXTR_PREFIX_IF_EXISTS - Only add prefix to variables if the same variable exists in the current symbol table
  • EXTR_REFS - Extracts variables as references. The imported variables are still referencing the values of the array parameter
  • prefixOptional. If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS are used in the extract_rules parameter, a specified prefix is required. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character.

    Technical Details

    Return Value: Returns the number of variables extracted on success
    PHP Version: 4+
    PHP Changelog: The extract_rules value EXTR_REFS was added in PHP 4.3. The extract_rules values EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS were added in PHP 4.2.As of PHP 4.0.5, this function now returns the number of variables extracted.The extract_rules value EXTR_PREFIX_INVALID was added in PHP 4.0.5.As of PHP 4.0.5, the extract_rules value EXTR_PREFIX_ALL now includes numeric variables as well.

    More Examples

    Example

    Using all parameters: <?php $a = "Original"; $my_array = array("a" => "Cat", "b" => "Dog", "c" => "Horse"); extract($my_array, EXTR_PREFIX_SAME, "dup"); echo "\$a = $a; \$b = $b; \$c = $c; \$dup_a = $dup_a";?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Search for the value "Glenn" in an array and output some text: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) { echo "Match found"; } else { echo "Match not found"; } ?> Try it Yourself »

    Definition and Usage

    The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

    Syntax

    in_array(search, array, type)

    Parameter Values

    ParameterDescription
    searchRequired. Specifies the what to search for
    arrayRequired. Specifies the array to search
    type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array.

    Technical Details

    Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
    PHP Version: 4+
    PHP Changelog: PHP 4.2: The search parameter may now be an array

    More Examples

    Example

    Using all parameters: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland", 23);if (in_array("23", $people, TRUE)) { echo "Match found<br>"; } else { echo "Match not found<br>"; } if (in_array("Glenn",$people, TRUE)) { echo "Match found<br>"; }else { echo "Match not found<br>"; }if (in_array(23,$people, TRUE)) { echo "Match found<br>"; }else { echo "Match not found<br>"; }?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return the element key from the current internal pointer position: <?php $people=array("Peter","Joe","Glenn","Cleveland"); echo "The key from the current position is: " . key($people);?> Try it Yourself »

    Definition and Usage

    The key() function returns the element key from the current internal pointer position. This function returns FALSE on error.

    Syntax

    key(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the key of the array element that is currently being pointed to by the internal pointer
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort an associative array in descending order, according to the key: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); krsort($age);?> Try it Yourself »

    Definition and Usage

    The krsort() function sorts an associative array in descending order, according to the key. Tip: Use the ksort() function to sort an associative array in ascending order, according to the key. Tip: Use the arsort() function to sort an associative array in descending order, according to the value.

    Syntax

    krsort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort an associative array in ascending order, according to the key: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); ksort($age);?> Try it Yourself »

    Definition and Usage

    The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

    Syntax

    ksort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Assign variables as if they were an array: <?php $my_array = array("Dog","Cat","Horse"); list($a, $b, $c) = $my_array; echo "I have several animals, a $a, a $b and a $c."; ?> Try it Yourself »

    Definition and Usage

    The list() function is used to assign values to a list of variables in one operation. Note: Prior to PHP 7.1, this function only worked on numerical arrays.

    Syntax

    list(var1, var2, ...)

    Parameter Values

    ParameterDescription
    var1Required. The first variable to assign a value to
    var2,...Optional. More variables to assign values to

    Technical Details

    Return Value: Returns the assigned array
    PHP Version: 4+

    More Examples

    Example

    Using the first and third variables: <?php $my_array = array("Dog","Cat","Horse"); list($a, , $c) = $my_array; echo "Here I only use the $a and $c variables.";?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Assign variables as if they were an array: <?php $temp_files = array("temp15.txt","Temp10.txt", "temp1.txt","Temp22.txt","temp2.txt"); natsort($temp_files); echo "Natural order: "; print_r($temp_files); echo "<br />"; natcasesort($temp_files); echo "Natural order case insensitve: "; print_r($temp_files); ?> The output of the code above will be: Natural order: Array ( [0] => Temp10.txt [1] => Temp22.txt [2] => temp1.txt [4] => temp2.txt [3] => temp15.txt ) Natural order case insensitve: Array ( [2] => temp1.txt [4] => temp2.txt [0] => Temp10.txt [3] => temp15.txt [1] => Temp22.txt )

    Definition and Usage

    The natcasesort() function sorts an array by using a "natural order" algorithm. The values keep their original keys. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2. This function is case-insensitive.

    Syntax

    natcasesort(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort an array: <?php $temp_files = array("temp15.txt","temp10.txt", "temp1.txt","temp22.txt","temp2.txt"); sort($temp_files); echo "Standard sorting: "; print_r($temp_files); echo "<br>"; natsort($temp_files); echo "Natural order: "; print_r($temp_files); ?> Try it Yourself »

    Definition and Usage

    The natsort() function sorts an array by using a "natural order" algorithm. The values keep their original keys. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2.

    Syntax

    natsort(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort

    Technical Details

    Return Value: Returns TRUE on success, or FALSE on failure.
    PHP Version: 4+
    PHP Changelog: PHP 5.2.1: Zero padded numeric strings (e.g., '00006') now ignore the 0 padding
    PHP Array Reference PHP Array Reference

    Example

    Output the value of the current and the next element in the array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; echo next($people); ?> Try it Yourself »

    Definition and Usage

    The next() function moves the internal pointer to, and outputs, the next element in the array. Related methods:
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • reset() - moves the internal pointer to the first element of the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    next(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the next element in the array on success, or FALSE if there are no more elements
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Output the value of the current element in an array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo pos($people) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The pos() function returns the value of the current element in an array. This function is an alias of the current() function. Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. Tip: This function does not move the arrays internal pointer. Related methods:
  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • reset() - moves the internal pointer to the first element of the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    pos(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the current element in an array, or FALSE on empty elements or elements with no value
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Output the value of the current, next and previous element in the array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; echo next($people) . "<br>"; echo prev($people); ?> Try it Yourself »

    Definition and Usage

    The prev() function moves the internal pointer to, and outputs, the previous element in the array. Related methods:
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • reset() - moves the internal pointer to the first element of the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    prev(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the previous element in the array on success, or FALSE if there are no more elements
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Create an array containing a range of elements from "0" to "5": <?php $number = range(0,5); print_r ($number); ?> Try it Yourself »

    Definition and Usage

    The range() function creates an array containing a range of elements. This function returns an array of elements from low to high. Note: If the low parameter is higher than the high parameter, the range array will be from high to low.

    Syntax

    range(low, high, step)

    Parameter Values

    ParameterDescription
    lowRequired. Specifies the lowest value of the array
    highRequired. Specifies the highest value of the array
    stepOptional. Specifies the increment used in the range. Default is 1

    Technical Details

    Return Value: Returns an array of elements from low to high
    PHP Version: 4+
    PHP Changelog: The step parameter was added in PHP 5.0.In PHP versions 4.1.0 through 4.3.2, this function sees numeric strings as strings and not integers. The numeric strings will be used for character sequences, e.g., "5252" is treated as "5".Support for character sequences and decrementing arrays was added in PHP 4.1.0. Character sequence values are limited to a length of one. If the length is higher than one, only the first character is used. Before this version, range() only generated incrementing integer arrays.

    More Examples

    Example

    Return an array of elements from "0" to "50" and increment by 10. <?php $number = range(0,50,10); print_r ($number);?> Try it Yourself »

    Example

    Using letters - return an array of elements from "a" to "d" <?php $letter = range("a","d"); print_r ($letter);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Output the value of the current and next element in an array, then reset the array's internal pointer to the first element in the array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; echo next($people) . "<br>"; echo reset($people); ?> Try it Yourself »

    Definition and Usage

    The reset() function moves the internal pointer to the first element of the array. Related methods:
  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • each() - returns the current element key and value, and moves the internal pointer forward
  • Syntax

    reset(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns the value of the first element in the array on success, or FALSE if the array is empty
    PHP Version: 4+

    More Examples

    Example

    A demonstration of all related methods: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");echo current($people) . "<br>"; // The current element is Peterecho next($people) . "<br>"; // The next element of Peter is Joeecho current($people) . "<br>"; // Now the current element is Joeecho prev($people) . "<br>"; // The previous element of Joe is Peterecho end($people) . "<br>"; // The last element is Clevelandecho prev($people) . "<br>"; // The previous element of Cleveland is Glennecho current($people) . "<br>"; // Now the current element is Glennecho reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Sort the elements of the $cars array in descending alphabetical order: <?php $cars=array("Volvo","BMW","Toyota");rsort($cars);?> Try it Yourself »

    Definition and Usage

    The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.

    Syntax

    rsort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+

    More Examples

    Example

    Sort the elements of the $numbers array in descending numerical order: <?php $numbers=array(4,6,2,22,11);rsort($numbers);?> Try it Yourself »

    Example

    Compare the items numerically and sort the elements of the $cars array in descending order: <?php $cars=array("Volvo","BMW","Toyota");rsort($cars,SORT_NUMERIC);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Randomize the order of the elements in the array: <?php $my_array = array("red","green","blue","yellow","purple");shuffle($my_array); print_r($my_array); ?> Try it Yourself »

    Definition and Usage

    The shuffle() function randomizes the order of the elements in the array. This function assigns new keys for the elements in the array. Existing keys will be removed (See Example below).

    Syntax

    shuffle(array)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to use

    Technical Details

    Return Value: Returns TRUE on success or FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 4.2: The random number generator is seeded automatically

    More Examples

    Example

    Randomize the order of the elements in the array: <?php $my_array = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"purple"); shuffle($my_array);print_r($my_array);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Return the number of elements in an array: <?php $cars=array("Volvo","BMW","Toyota");echo sizeof($cars);?> Try it Yourself »

    Definition and Usage

    The sizeof() function returns the number of elements in an array. The sizeof() function is an alias of the count() function.

    Syntax

    sizeof(array, mode)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array
    modeOptional. Specifies the mode. Possible values:
  • 0 - Default. Does not count all elements of multidimensional arrays
  • 1 - Counts the array recursively (counts all the elements of multidimensional arrays)
  • Technical Details

    Return Value: Returns the number of elements in the array
    PHP Version: 4+

    More Examples

    Example

    Count the array recursively: <?php $cars=array ( "Volvo"=>array ( "XC60", "XC90" ), "BMW"=>array ( "X3", "X5" ), "Toyota"=>array ( "Highlander" ) ); echo "Normal count: " . sizeof($cars)."<br>";echo "Recursive count: " . sizeof($cars,1);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Sort the elements of the $cars array in ascending alphabetical order: <?php $cars=array("Volvo","BMW","Toyota");sort($cars);?> Try it Yourself »

    Definition and Usage

    The sort() function sorts an indexed array in ascending order. Tip: Use the rsort() function to sort an indexed array in descending order.

    Syntax

    sort(array, sorttype)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (don't change types)
  • 1 = SORT_NUMERIC - Compare items numerically
  • 2 = SORT_STRING - Compare items as strings
  • 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale
  • 4 = SORT_NATURAL - Compare items as strings using natural ordering
  • 5 = SORT_FLAG_CASE -
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+

    More Examples

    Example

    Sort the elements of the $numbers array in ascending numerical order: <?php $numbers=array(4,6,2,22,11);sort($numbers);?> Try it Yourself » PHP Array Reference PHP Array Reference

    Example

    Sort the elements of the $arr array by values using a user-defined comparison function: <?php function my_sort($a,$b){if ($a==$b) return 0;return ($a<$b)?-1:1;}$arr=array("a"=>4,"b"=>2,"c"=>8,"d"=>6); uasort($arr,"my_sort");?> Try it Yourself »

    Definition and Usage

    The uasort() function sorts an array by values using a user-defined comparison function. Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.

    Syntax

    uasort(array, myfunction)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    myfunctionOptional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort the elements of the $arr array by keys using a user-defined comparison function: <?php function my_sort($a,$b){if ($a==$b) return 0;return ($a<$b)?-1:1;}$arr=array("a"=>4,"b"=>2,"c"=>8,"d"=>6); uksort($arr,"my_sort");?> Try it Yourself »

    Definition and Usage

    The uksort() function sorts an array by keys using a user-defined comparison function. Tip: Use the uasort() function to sort an array by values using a user-defined comparison function.

    Syntax

    uksort(array, myfunction)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    myfunctionOptional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference PHP Array Reference

    Example

    Sort the elements of the $a array using a user-defined comparison function: <?php function my_sort($a,$b){if ($a==$b) return 0;return ($a<$b)?-1:1;}$a=array(4,2,8,6);usort($a,"my_sort");?> Try it Yourself »

    Definition and Usage

    The usort() function sorts an array using a user-defined comparison function.

    Syntax

    usort(array, myfunction)

    Parameter Values

    ParameterDescription
    arrayRequired. Specifies the array to sort
    myfunctionOptional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Array Reference

    Calendar Introduction

    The calendar extension contains functions that simplifies converting between different calendar formats. It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C. Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice. Note: The Julian Day Count is not the same as the Julian Calendar!

    Installation

    For these functions to work, you have to compile PHP with --enable-calendar. The Windows version of PHP has built-in support for this extension.

    Calendar Functions

    FunctionDescription
    cal_days_in_month()Returns the number of days in a month for a specified year and calendar
    cal_from_jd()Converts a Julian Day Count into a date of a specified calendar
    cal_info()Returns information about a specified calendar
    cal_to_jd()Converts a date in a specified calendar to Julian Day Count
    easter_date()Returns the Unix timestamp for midnight on Easter of a specified year
    easter_days()Returns the number of days after March 21, that the Easter Day is in a specified year
    frenchtojd()Converts a French Republican date to a Julian Day Count
    gregoriantojd()Converts a Gregorian date to a Julian Day Count
    jddayofweek()Returns the day of the week
    jdmonthname()Returns a month name
    jdtofrench()Converts a Julian Day Count to a French Republican date
    jdtogregorian()Converts a Julian Day Count to a Gregorian date
    jdtojewish()Converts a Julian Day Count to a Jewish date
    jdtojulian()Converts a Julian Day Count to a Julian date
    jdtounix()Converts Julian Day Count to Unix timestamp
    jewishtojd()Converts a Jewish date to a Julian Day Count
    juliantojd()Converts a Julian date to a Julian Day Count
    unixtojd()Converts Unix timestamp to Julian Day Count

    Predefined Calendar Constants

    ConstantTypePHP Version
    CAL_GREGORIANIntegerPHP 4
    CAL_JULIANIntegerPHP 4
    CAL_JEWISHIntegerPHP 4
    CAL_FRENCHIntegerPHP 4
    CAL_NUM_CALSIntegerPHP 4
    CAL_DOW_DAYNOIntegerPHP 4
    CAL_DOW_SHORTIntegerPHP 4
    CAL_DOW_LONGIntegerPHP 4
    CAL_MONTH_GREGORIAN_SHORTIntegerPHP 4
    CAL_MONTH_GREGORIAN_LONGIntegerPHP 4
    CAL_MONTH_JULIAN_SHORTIntegerPHP 4
    CAL_MONTH_JULIAN_LONGIntegerPHP 4
    CAL_MONTH_JEWISHIntegerPHP 4
    CAL_MONTH_FRENCHIntegerPHP 4
    CAL_EASTER_DEFAULTIntegerPHP 4.3
    CAL_EASTER_ROMANIntegerPHP 4.3
    CAL_EASTER_ALWAYS_GREGORIANIntegerPHP 4.3
    CAL_EASTER_ALWAYS_JULIANIntegerPHP 4.3
    CAL_JEWISH_ADD_ALAFIM_GERESHIntegerPHP 5.0
    CAL_JEWISH_ADD_ALAFIMIntegerPHP 5.0
    CAL_JEWISH_ADD_GERESHAYIMIntegerPHP 5.0
    PHP Calendar Reference

    Example

    Get the number of days in a month for a specified year and calendar: <?php $d=cal_days_in_month(CAL_GREGORIAN,10,2005);echo "There was $d days in October 2005";?> Run Example »

    Definition and Usage

    The cal_days_in_month() function returns the number of days in a month for a specified year and calendar.

    Syntax

    cal_days_in_month(calendar,month,year);

    Parameter Values

    ParameterDescription
    calendarRequired. Specifies the calendar to use. Look at the PHP Calendar Constants
    monthRequired. Specifies the month in the selected calendar
    yearRequired. Specifies the year in the selected calendar

    Technical Details

    Return Value: The number of days in the selected month, in the given year and calendar
    PHP Version: 4.1+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Julian Day Count into a date of in the Gregorian calendar: <?php $d=unixtojd(mktime(0,0,0,6,20,2007)); print_r(cal_from_jd($d,CAL_GREGORIAN));?> Run Example »

    Definition and Usage

    The cal_from_jd() function converts a Julian Day Count into a date of a specified calendar.

    Syntax

    cal_from_jd(jd,calendar);

    Parameter Values

    ParameterDescription
    jdRequired. Specifies a Julian Day as an integer
    calendarRequired. Specifies the calendar to convert to. Must be one of the following values:
  • CAL_GREGORIAN
  • CAL_JULIAN
  • CAL_JEWISH
  • CAL_FRENCH
  • Technical Details

    Return Value: Returns an array that contains calendar information like:
  • date in form "month/day/year"
  • month
  • year
  • day of week
  • abbreviated and full names of weekday and month
  • PHP Version: 4.1+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Return information about the Gregorian calendar: <?php print_r(cal_info(0));?> Run Example »

    Definition and Usage

    The cal_info() function returns information about a specified calendar.

    Syntax

    cal_info(calendar);

    Parameter Values

    ParameterDescription
    calendarOptional. Specifies a number that indicates which calendar to return information about:
  • 0 = CAL_GREGORIAN
  • 1 = CAL_JULIAN
  • 2 = CAL_JEWISH
  • 3 = CAL_FRENCH
  • Tip: If the calendar parameter is omitted, cal_info() returns info about all calendars

    Technical Details

    Return Value: Returns an array containing calendar elements like:
  • calname
  • calsymbol
  • month
  • abbrevmonth
  • maxdaysinmonth
  • PHP Version: 4.1+
    Changelog: In PHP 5.0 the calendar parameter became optional
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert 20th of June, 2007 (Gregorian calendar) to Julian Day Count: <?php $d=cal_to_jd(CAL_GREGORIAN,6,20,2007);echo $d;?> Run Example »

    Definition and Usage

    The cal_to_jd() function converts a date in a specified calendar to Julian Day Count.

    Syntax

    cal_to_jd(calendar,month,day,year);

    Parameter Values

    ParameterDescription
    calendarRequired. Specifies the calendar to convert from. Must be one of the following values:
  • CAL_GREGORIAN
  • CAL_JULIAN
  • CAL_JEWISH
  • CAL_FRENCH
  • monthRequired. Specifies the month as a number
    dayRequired. Specifies the day as a number
    yearRequired. Specifies the year as a number

    Technical Details

    Return Value: Returns a Julian Day number
    PHP Version: 4.1+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Print the easter date for different years: <?php echo easter_date() . "<br />";echo date("M-d-Y",easter_date()) . "<br />";echo date("M-d-Y",easter_date(1975)) . "<br />";echo date("M-d-Y",easter_date(1998)) . "<br />";echo date("M-d-Y",easter_date(2007));?> Run Example »

    Definition and Usage

    The easter_date() function returns the Unix timestamp for midnight on Easter of a given year. Tip: The date of Easter Day is defined as the Sunday after the first full moon which falls on or after the Spring Equinox (21st March).

    Syntax

    easter_date(year);

    Parameter Values

    ParameterDescription
    yearOptional. Specifies a year between 1970 and 2037. Default is the current year, local time

    Technical Details

    Return Value: Returns the easter date as a unix timestamp
    PHP Version: 4+
    Changelog: In PHP 4.3 the year parameter became optional
    PHP Calendar Reference PHP Calendar Reference

    Example

    Print the number of days after March 21, that the Easter Day is/was for different years: <?php echo "Easter Day is ". easter_days() . " days after March 21 this year.<br />";echo "Easter Day was ". easter_days(1990) . " days after March 21 in 1990.<br />";echo "Easter Day was ". easter_days(1342) . " days after March 21 in 1342.<br />";echo "Easter Day will be ". easter_days(2050) . " days after March 21 in 2050.";?> Run Example »

    Definition and Usage

    The easter_days() function returns the number of days after March 21, that the Easter Day is in the given year. Tip: The date of Easter Day is defined as the Sunday after the first full moon which falls on or after the Spring Equinox (21st March).

    Syntax

    easter_days(year,method);

    Parameter Values

    ParameterDescription
    yearOptional. Specifies a year as a number. Default is the current year, local time
    methodOptional. Allows you to calculate easter dates based on other calendars. E.g. it uses the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN

    Technical Details

    Return Value: Returns the number of days after March 21, that the Easter Day is in the given year
    PHP Version: 4+
    Changelog: In PHP 4.3 the year parameter became optional and the method parameter was added
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a French Republican date to a Julian Day Count and back to a French Republican date: <?php $jd=frenchtojd(3,3,14);echo $jd . "<br>";echo jdtofrench($jd);?> Run Example »

    Definition and Usage

    The frenchtojd() function converts a date from the French Republican Calendar to a Julian Day Count. Tip: The French Republican Calendar is a calendar proposed during the French Revolution, and used by the French government for about twelve years from late 1793. This function only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 - 22 September 1806). Tip: Look at the jdtofrench() function to convert a Julian Day Count to a French Republican date.

    Syntax

    frenchtojd(month,day,year);

    Parameter Values

    ParameterDescription
    monthRequired. Specifies the month as a number from 1 to 13
    dayRequired. Specifies the day as a number from 1 to 30
    yearRequired. Specifies the year as a number from 1 to 14

    Technical Details

    Return Value: Returns a Julian Day number
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Gregorian date to a Julian Day Count and back to a Gregorian date: <?php $jd=gregoriantojd(6,20,2007);echo $jd . "<br>";echo jdtogregorian($jd);?> Run Example »

    Definition and Usage

    The gregoriantojd() function converts a date from the Gregorian Calendar to a Julian Day Count. Note: Although this function can handle dates back to 4714 B.C., notice that the Gregorian calendar was not instituted until 1582, and some countries did not accept it until much later (Britain converted in 1752, USSR in 1918, and Greece in 1923). Most European countries used the Julian calendar prior the Gregorian. Tip: Look at the jdtogregorian() function to convert a Julian Day Count to a Gregorian date.

    Syntax

    gregoriantojd(month,day,year);

    Parameter Values

    ParameterDescription
    monthRequired. Specifies the month as a number from 1 to 12
    dayRequired. Specifies the day as a number from 1 to 31
    yearRequired. Specifies the year as a number between -4714 and 9999

    Technical Details

    Return Value: Returns a Julian Day number
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Return the weekday of 13th January, 1998: <?php $jd=gregoriantojd(1,13,1998);echo jddayofweek($jd,1);?> Run Example »

    Definition and Usage

    The jddayofweek() function returns the day of the week.

    Syntax

    jddayofweek(jd,mode);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number
    modeOptional. Specifies how to return the weekday. Can have one of the following values:
  • 0 - Default. Returns the weekday as an integer (0=Sunday, 1=Monday, etc.)
  • 1 - Returns the weekday as a string (Sunday, Monday, etc.)
  • 2 - Returns the weekday as a string, abbreviated form (Sun, Mon, etc.)
  • Technical Details

    Return Value: Returns the Gregorian weekday as a string or integer (depends on the mode parameter)
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Return the abbreviated Gregorian monthname of 13th January, 1998: <?php $jd=gregoriantojd(1,13,1998);echo jdmonthname($jd,0);?> Run Example »

    Definition and Usage

    The jdmonthname() function returns a month name.

    Syntax

    jdmonthname(jd,mode);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number
    modeOptional. Specifies which calendar to convert the Julian Day Count to, and how the month name is to be returned. Mode values:
  • 0 - Gregorian - abbreviated form (Jan, Feb, Mar, etc.)
  • 1 - Gregorian (January, February, March, etc.)
  • 2 - Julian - abbreviated form (Jan, Feb, Mar, etc.)
  • 3 - Julian (January, February, March, etc.)
  • 4 - Jewish (Tishri, Heshvan, Kislev, etc.)
  • 5 - French Republican (Vendemiaire, Brumaire, Frimaire, etc.)
  • Technical Details

    Return Value: Returns the month name for the specified Julian Day and calendar
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a French Republican date to a Julian Day Count and back to a French Republican date: <?php $jd=frenchtojd(3,3,14);echo $jd . "<br>";echo jdtofrench($jd);?> Run Example »

    Definition and Usage

    The jdtofrench() function converts a Julian Day Count to a French Republican date. Tip: Look at the frenchtojd() function to convert a French Republican date to a Julian Day Count.

    Syntax

    jdtofrench(jd);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number

    Technical Details

    Return Value: Returns a French Republican date in format "month/day/year"
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Gregorian date to a Julian Day Count and back to a Gregorian date: <?php $jd=gregoriantojd(6,20,2007);echo $jd . "<br>";echo jdtogregorian($jd);?> Run Example »

    Definition and Usage

    The jdtogregorian() function converts a Julian Day Count to a Gregorian date. Tip: Look at the gregoriantojd() function to convert a Gregorian date to a Julian Day Count.

    Syntax

    jdtogregorian(jd);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number

    Technical Details

    Return Value: Returns a Gregorian date in format "month/day/year"
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Julian Day Count to a Jewish date: <?php $jd=jdtojewish(1789430); echo $jd;?> Run Example »

    Definition and Usage

    The jdtojewish() function converts a Julian Day Count to a Jewish date. Tip: Look at the jewishtojd() function to convert a Jewish date to a Julian Day Count.

    Syntax

    jdtojewish(jd,hebrew,fl);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number
    hebrewOptional. When set to TRUE it indicates Hebrew output format. FALSE is default
    flOptional. Defines the Hebrew output format. The available formats are:
  • CAL_JEWISH_ADD_ALAFIM_GERESH
  • CAL_JEWISH_ADD_ALAFIM
  • CAL_JEWISH_ADD_GERESHAYIM
  • Technical Details

    Return Value: Returns a Jewish date in format "month/day/year"
    PHP Version: 4+
    Changelog: The hebrew parameter was added in PHP 4.3, and the fl parameter was added in PHP 5.0
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Julian date to a Julian Day Count and back to a Julian date: <?php $jd=juliantojd(6,20,2007);echo $jd . "<br>";echo jdtojulian($jd);?> Run Example »

    Definition and Usage

    The jdtojulian() function converts a Julian Day Count to a Julian date. Tip: Look at the juliantojd() function to convert a Julian date to a Julian Day Count.

    Syntax

    jdtojulian(jd);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number

    Technical Details

    Return Value: Returns a Julian date in format "month/day/year"
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Gregorian date to a Julian Day Count; then convert the Julian Day Count to Unix timestamp: <?php $jd=gregoriantojd(10,3,1975);echo jdtounix($jd);?> Run Example »

    Definition and Usage

    The jdtounix() function converts Julian Day Count to Unix timestamp. Note: This function will return false if the parameter jd is not inside the Unix epoch (which means that the Gregorian years must be between 1970 and 2037 OR that jd >= 2440588 and jd <= 2465342). The time returned is local time. Tip: Look at the unixtojd() function to convert Unix timestamp to Julian Day Count.

    Syntax

    jdtounix(jd);

    Parameter Values

    ParameterDescription
    jdRequired. A Julian Day number between 2440588 and 2465342

    Technical Details

    Return Value: Returns the Unix timestamp for the start of the specified Julian day
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Jewish date to a Julian Day Count: <?php $jd=jewishtojd(6,20,2007);echo $jd;?> Run Example »

    Definition and Usage

    The jewishtojd() function converts a date from the Jewish Calendar to a Julian Day Count. Note: Although this function can handle dates back to year 1 (3761 B.C.), notice that in the beginning there was no formula to determine the start of a month. A new month was started when the new moon was first observed. Tip: Look at the jdtojewish() function to convert a Julian Day Count to a Jewish date.

    Syntax

    jewishtojd(month,day,year);

    Parameter Values

    ParameterDescription
    monthRequired. Specifies the month as a number from 1 to 13
    dayRequired. Specifies the day as a number from 1 to 30
    yearRequired. Specifies the year as a number between 1 and 9999

    Technical Details

    Return Value: Returns a Julian Day number
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert a Julian date to a Julian Day Count and back to a Julian date: <?php $jd=juliantojd(6,20,2007);echo $jd . "<br>";echo jdtojulian($jd);?> Run Example »

    Definition and Usage

    The juliantojd() function converts a date from the Julian Calendar to a Julian Day Count. Note: Although this function can handle dates back to 4713 B.C., notice that the Julian calendar was created in 46 B.C., and it did not stabilize until at least 8 A.D. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month. Remember that the current calendar being used worldwide is the Gregorian calendar. The gregoriantojd() function can be used to convert such dates to their Julian Day count. Tip: Look at the jdtojulian() function to convert a Julian Day Count to a Julian date.

    Syntax

    juliantojd(month,day,year);

    Parameter Values

    ParameterDescription
    monthRequired. Specifies the month as a number from 1 to 12
    dayRequired. Specifies the day as a number from 1 to 31
    yearRequired. Specifies the year as a number between -4713 and 9999

    Technical Details

    Return Value: Returns a Julian Day number
    PHP Version: 4+
    PHP Calendar Reference PHP Calendar Reference

    Example

    Convert Unix timestamp to Julian Day Count: <?php echo unixtojd();?> Run Example »

    Definition and Usage

    The unixtojd() function converts Unix timestamp to Julian Day Count. Note: Unix timestamp indicates the number of seconds since midnight of January 1, 1970 (Gregorian Calendar). Tip: Look at the jdtounix() function to convert Julian Day Count to Unix timestamp.

    Syntax

    unixtojd(timestamp);

    Parameter Values

    ParameterDescription
    timestampOptional. Specifies A unix timestamp to convert

    Technical Details

    Return Value: Returns the Julian Day number for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given
    PHP Version: 4+
    PHP Calendar Reference

    Date/Time Introduction

    The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways. Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions.

    Installation

    The PHP date/time functions are part of the PHP core. No installation is required to use these functions.

    Runtime Configuration

    The behavior of these functions is affected by settings in php.ini:
    NameDescriptionDefaultPHP Version
    date.timezoneThe default timezone (used by all date/time functions)"PHP 5.1
    date.default_latitudeThe default latitude (used by date_sunrise() and date_sunset()) "31.7667"PHP 5.0
    date.default_longitudeThe default longitude (used by date_sunrise() and date_sunset())"35.2333"PHP 5.0
    date.sunrise_zenithThe default sunrise zenith (used by date_sunrise() and date_sunset())"90.83"PHP 5.0
    date.sunset_zenithThe default sunset zenith (used by date_sunrise() and date_sunset())"90.83"PHP 5.0

    Date/Time Functions

    FunctionDescription
    checkdate()Validates a Gregorian date
    date_add()Adds days, months, years, hours, minutes, and seconds to a date
    date_create_from_format()Returns a new DateTime object formatted according to a specified format
    date_create()Returns a new DateTime object
    date_date_set()Sets a new date
    date_default_timezone_get()Returns the default timezone used by all date/time functions
    date_default_timezone_set()Sets the default timezone used by all date/time functions
    date_diff()Returns the difference between two dates
    date_format()Returns a date formatted according to a specified format
    date_get_last_errors()Returns the warnings/errors found in a date string
    date_interval_create_from_date_string()Sets up a DateInterval from the relative parts of the string
    date_interval_format()Formats the interval
    date_isodate_set()Sets the ISO date
    date_modify()Modifies the timestamp
    date_offset_get()Returns the timezone offset
    date_parse_from_format()Returns an associative array with detailed info about a specified date, according to a specified format
    date_parse()Returns an associative array with detailed info about a specified date
    date_sub()Subtracts days, months, years, hours, minutes, and seconds from a date
    date_sun_info()Returns an array containing info about sunset/sunrise and twilight begin/end, for a specified day and location
    date_sunrise()Returns the sunrise time for a specified day and location
    date_sunset()Returns the sunset time for a specified day and location
    date_time_set()Sets the time
    date_timestamp_get()Returns the Unix timestamp
    date_timestamp_set()Sets the date and time based on a Unix timestamp
    date_timezone_get()Returns the time zone of the given DateTime object
    date_timezone_set()Sets the time zone for the DateTime object
    date()Formats a local date and time
    getdate()Returns date/time information of a timestamp or the current local date/time
    gettimeofday()Returns the current time
    gmdate()Formats a GMT/UTC date and time
    gmmktime()Returns the Unix timestamp for a GMT date
    gmstrftime()Formats a GMT/UTC date and time according to locale settings
    idate()Formats a local time/date as integer
    localtime()Returns the local time
    microtime()Returns the current Unix timestamp with microseconds
    mktime()Returns the Unix timestamp for a date
    strftime()Formats a local time and/or date according to locale settings
    strptime()Parses a time/date generated with strftime()
    strtotime()Parses an English textual datetime into a Unix timestamp
    time()Returns the current time as a Unix timestamp
    timezone_abbreviations_list()Returns an associative array containing dst, offset, and the timezone name
    timezone_identifiers_list()Returns an indexed array with all timezone identifiers
    timezone_location_get()Returns location information for a specified timezone
    timezone_name_from_ abbr()Returns the timezone name from abbreviation
    timezone_name_get()Returns the name of the timezone
    timezone_offset_get()Returns the timezone offset from GMT
    timezone_open()Creates new DateTimeZone object
    timezone_transitions_get()Returns all transitions for the timezone
    timezone_version_get()Returns the version of the timezonedb

    Predefined Date/Time Constants

    ConstantDescription
    DATE_ATOMAtom (example: 2019-01-18T14:13:03+00:00)
    DATE_COOKIEHTTP Cookies (example: Fri, 18 Jan 2019 14:13:03 UTC)
    DATE_ISO8601ISO-8601 (example: 2019-01-18T14:13:03+0000)
    DATE_RFC822RFC 822 (example: Fri, 18 Jan 2019 14:13:03 +0000)
    DATE_RFC850RFC 850 (example: Friday, 18-Jan-19 14:13:03 UTC)
    DATE_RFC1036RFC 1036 (example: Friday, 18-Jan-19 14:13:03 +0000)
    DATE_RFC1123RFC 1123 (example: Fri, 18 Jan 2019 14:13:03 +0000)
    DATE_RFC2822RFC 2822 (example: Fri, 18 Jan 2019 14:13:03 +0000)
    DATE_RFC3339Same as DATE_ATOM (since PHP 5.1.3)
    DATE_RFC3339_EXTENDEDRFC3339 Extended format (since PHP 7.0.0) (example: 2019-01-18T16:34:01.000+00:00)
    DATE_RSSRSS (Fri, 18 Jan 2019 14:13:03 +0000)
    DATE_W3CWorld Wide Web Consortium (example: 2019-01-18T14:13:03+00:00)
    SUNFUNCS_RET_TIMESTAMPTimestamp (since PHP 5.1.2)
    SUNFUNCS_RET_STRINGHours:minutes (example: 09:41) (since PHP 5.1.2)
    SUNFUNCS_RET_DOUBLEHours as a floating point number (example: 9.75) (since PHP 5.1.2)
    PHP Date/Time Reference

    Example

    Check if several dates are valid Gregorian dates: <?php var_dump(checkdate(12,31,-400));echo "<br>"; var_dump(checkdate(2,29,2003));echo "<br>"; var_dump(checkdate(2,29,2004));?> Try it Yourself »

    Definition and Usage

    The checkdate() function is used to validate a Gregorian date.

    Syntax

    checkdate(month, day, year)

    Parameter Values

    ParameterDescription
    monthRequired. Specifies the month as a number between 1 and 12
    dayRequired. Specifies the day as a number between 1 and 31
    yearRequired. Specifies the year as a number between 1 and 32767

    Technical Details

    Return Value: TRUE if the date is valid. FALSE otherwise
    PHP Version: 4.0+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Add 40 days to the 15th of March, 2013: <?php $date=date_create("2013-03-15"); date_add($date,date_interval_create_from_date_string("40 days")); echo date_format($date,"Y-m-d");?> Try it Yourself »

    Definition and Usage

    The date_add() function adds some days, months, years, hours, minutes, and seconds to a date.

    Syntax

    date_add(object, interval)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    intervalRequired. Specifies a DateInterval object

    Technical Details

    Return Value: Returns a DateTime object on success. FALSE on failure
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return a new DateTime object formatted according to the specified format: <?php $date=date_create_from_format("j-M-Y","15-Mar-2013");?> Try it Yourself »

    Definition and Usage

    The date_create_from_format() function returns a new DateTime object formatted according to the specified format.

    Syntax

    date_create_from_format(format, time, timezone)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format to use. The following characters can be used in the format parameter string:
  • d - Day of the month; with leading zeros
  • j - Day of the month; without leading zeros
  • D - Day of the month (Mon - Sun)
  • l - Day of the month (Monday - Sunday)
  • S - English suffix for day of the month (st, nd, rd, th)
  • F - Monthname (January - December)
  • M - Monthname (Jan-Dec)
  • m - Month (01-12)
  • n - Month (1-12)
  • Y - Year (e.g 2013)
  • y - Year (e.g 13)
  • a and A - am or pm
  • g - 12 hour format without leading zeros
  • G - 24 hour format without leading zeros
  • h - 12 hour format with leading zeros
  • H - 24 hour format with leading zeros
  • i - Minutes with leading zeros
  • s - Seconds with leading zeros
  • u - Microseconds (up to six digits)
  • e, O, P and T - Timezone identifier
  • U - Seconds since Unix Epoch
  • (space)
  • # - One of the following separation symbol: ;,:,/,.,,,-,(,)
  • ? - A random byte
  • * - Rondom bytes until next separator/digit
  • ! - Resets all fields to Unix Epoch
  • | - Resets all fields to Unix Epoch if they have not been parsed yet
  • + - If present, trailing data in the string will cause a warning, not an error
  • timeRequired. Specifies a date/time string. NULL indicates the current date/time
    timezoneOptional. Specifies the timezone of time. Default is the current timezone

    Technical Details

    Return Value: Returns a new DateTime object on success. FALSE on failure
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return a new DateTime object, and then format the date: <?php $date=date_create("2013-03-15"); echo date_format($date,"Y/m/d");?> Try it Yourself » More examples at the bottom of this page.

    Definition and Usage

    The date_create() function returns a new DateTime object.

    Syntax

    date_create(time, timezone)

    Parameter Values

    ParameterDescription
    timeOptional. Specifies a date/time string. NULL indicates the current time
    timezoneOptional. Specifies the timezone of time. Default is the current timezone.Tip: Look at a list of all supported timezones in PHP

    Technical Details

    Return Value: Returns a new DateTime object on success. FALSE/Exception on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 7.1: Microseconds is now filled with actual value, not just "00000".PHP 5.3: An exception is thrown if time is an invalid value. Previously an error was thrown

    More Examples

    Example

    Return a new DateTime object (with a given timezone), and then format the date and time: <?php $date=date_create("2013-03-15 23:40:00",timezone_open("Europe/Oslo")); echo date_format($date,"Y/m/d H:iP");?> Try it Yourself » PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return a new DateTime object, set a new date, and then format the date: <?php $date=date_create();date_date_set($date,2020,10,30);echo date_format($date,"Y/m/d");?> Try it Yourself »

    Definition and Usage

    The date_date_set() function sets a new date.

    Syntax

    date_date_set(object, year, month, day)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    yearRequired. Specifies the year of the date
    monthRequired. Specifies the month of the date
    dayRequired. Specifies the day of the date

    Technical Details

    Return Value: Returns a new DateTime object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.3: The return value was changed from NULL to DateTime (on success)
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the default timezone: <?php echo date_default_timezone_get();?> Try it Yourself »

    Definition and Usage

    The date_default_timezone_get() function returns the default timezone used by all date/time functions in the script.

    Syntax

    date_default_timezone_get()

    Technical Details

    Return Value: Returns the timezone as a string
    PHP Version: 5.1+
    PHP Changelog: PHP 5.4: The TZ variable is no longer used to guess the timezone
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Set the default timezone: <?php date_default_timezone_set("Asia/Bangkok");echo date_default_timezone_get();?> Try it Yourself »

    Definition and Usage

    The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.

    Syntax

    date_default_timezone_set(timezone)

    Parameter Values

    ParameterDescription
    timezoneRequired. Specifies the timezone to use, like "UTC" or "Europe/Paris". List of valid timezones: http://www.php.net/manual/en/timezones.php

    Technical Details

    Return Value: Returns FALSE if the timezone is not valid. TRUE otherwise
    PHP Version: 5.1+
    PHP Changelog: PHP 5.3: Throws an E_WARNING instead of E_STRICT.PHP 5.1.2: Started to validate the timezone parameter.
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Calculate the difference between two dates: <?php $date1=date_create("2013-03-15");$date2=date_create("2013-12-12"); $diff=date_diff($date1,$date2);?> Try it Yourself »

    Definition and Usage

    The date_diff() function returns the difference between two DateTime objects.

    Syntax

    date_diff(datetime1, datetime2, absolute)

    Parameter Values

    ParameterDescription
    datetime1Required. Specifies a DateTime object
    datetime2Required. Specifies a DateTime object
    absoluteOptional. Specifies a Boolean value. TRUE indicates that the interval/difference MUST be positive. Default is FALSE

    Technical Details

    Return Value: Returns a DateInterval object on success that represents the difference between the two dates. FALSE on failure
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return a new DateTime object, and then format the date: <?php $date=date_create("2013-03-15");echo date_format($date,"Y/m/d H:i:s");?> Try it Yourself »

    Definition and Usage

    The date_format() function returns a date formatted according to the specified format. Note: This function does not use locales (all output is in English). Tip: Also look at the date() function, which formats a local date/time.

    Syntax

    date_format(object, format)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    formatRequired. Specifies the format for the date. The following characters can be used:
  • d - The day of the month (from 01 to 31)
  • D - A textual representation of a day (three letters)
  • j - The day of the month without leading zeros (1 to 31)
  • l (lowercase 'L') - A full textual representation of a day
  • N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
  • S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
  • w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
  • z - The day of the year (from 0 through 365)
  • W - The ISO-8601 week number of year (weeks starting on Monday)
  • F - A full textual representation of a month (January through December)
  • m - A numeric representation of a month (from 01 to 12)
  • M - A short textual representation of a month (three letters)
  • n - A numeric representation of a month, without leading zeros (1 to 12)
  • t - The number of days in the given month
  • L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
  • o - The ISO-8601 year number
  • Y - A four digit representation of a year
  • y - A two digit representation of a year
  • a - Lowercase am or pm
  • A - Uppercase AM or PM
  • B - Swatch Internet time (000 to 999)
  • g - 12-hour format of an hour (1 to 12)
  • G - 24-hour format of an hour (0 to 23)
  • h - 12-hour format of an hour (01 to 12)
  • H - 24-hour format of an hour (00 to 23)
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds, with leading zeros (00 to 59)
  • u - Microseconds (added in PHP 5.2.2)
  • e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
  • I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
  • O - Difference to Greenwich time (GMT) in hours (Example: +0100)
  • P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
  • T - Timezone abbreviations (Examples: EST, MDT)
  • Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
  • c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
  • r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
  • U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • and the following predefined constants can also be used (available since PHP 5.1.0):
  • DATE_ATOM - Atom (example: 2013-04-12T15:52:01+00:00)
  • DATE_COOKIE - HTTP Cookies (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
  • DATE_RFC822 - RFC 822 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC850 - RFC 850 (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_RFC1036 - RFC 1036 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC1123 - RFC 1123 (example: Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC2822 - RFC 2822 (Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC3339 - Same as DATE_ATOM (since PHP 5.1.3)
  • DATE_RSS - RSS (Fri, 12 Aug 2013 15:52:01 +0000)
  • DATE_W3C - World Wide Web Consortium (example: 2013-04-12T15:52:01+00:00)
  • Technical Details

    Return Value: Returns the formatted date as a string. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the warnings and errors while parsing a date string: <?php date_create("gyuiyiuyui%&&/"); print_r(date_get_last_errors());?> Try it Yourself »

    Definition and Usage

    The date_get_last_errors() function returns the warnings/errors found while parsing a date string.

    Syntax

    date_get_last_errors()

    Technical Details

    Return Value: Returns an array that contains information about the errors/warnings
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Use date_interval_create_from_date_string() to add 1 year and 35 days to a date: <?php $date = date_create('2019-01-01');date_add($date, date_interval_create_from_date_string('1 year 35 days'));echo date_format($date, 'Y-m-d');?> Try it Yourself »

    Definition and Usage

    The date_interval_create_from_date_string() function sets up a DateInterval from the relative parts of the string.

    Syntax

    date_interval_create_from_date_string(datetime)

    Parameter Values

    ParameterDescription
    datetimeRequired. Specifies a DateInterval

    Technical Details

    Return Value: Returns new DateInterval object
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Calculate the interval between two dates, then format the interval: <?php $date1=date_create("2013-01-01");$date2=date_create("2013-02-10"); $diff=date_diff($date1,$date2);// %a outputs the total number of daysecho $diff->format("Total number of days: %a.");?> Try it Yourself »

    Definition and Usage

    The date_interval_format() function is an alias of DateInterval::format(). The DateInterval::format() function is used to format the interval.

    Syntax

    DateInterval::format(format)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format. The following characters can be used in the format parameter string:
  • % - Literal %
  • Y - Year, at least 2 digits with leading zero (e.g 03)
  • y - Year (e.g 3)
  • M - Month, with leading zero (e.g 06)
  • m - Month (e.g 6)
  • D - Day, with leading zero (e.g 09)
  • d - Day (e.g 9)
  • a - Total number of days as a result of date_diff()
  • H - Hours, with leading zero (e.g 08, 23)
  • h - Hours (e.g 8, 23)
  • I - Minutes, with leading zero (e.g 08, 23)
  • i - Minutes (e.g 8, 23)
  • S - Seconds, with leading zero (e.g 08, 23)
  • s - Seconds (e.g 8, 23)
  • F - Microseconds, at least 6 digits (e.g 004403, 235689)
  • f - Microseconds (e.g 4403, 235689)
  • R - Sign "-" when negative, "+" when positive
  • r - Sign "-" when negative, empty when positive
  • Note: Each format character must be prefixed by a % sign!

    Technical Details

    Return Value: Returns the formatted interval
    PHP Version: 5.3+
    PHP Changelog: PHP 7.1: Added the F and f parameters
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Set the ISO date to the 5th week in 2013: <?php $date=date_create();date_isodate_set($date,2013,5);echo date_format($date,"Y-m-d");?> Try it Yourself »

    Definition and Usage

    The date_isodate_set() function sets a date according to the ISO 8601 standard, using weeks and day offsets (instead of using a specific date).

    Syntax

    date_isodate_set(object, year, week, day)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    yearRequired. Specifies the year of the date
    weekRequired. Specifies the week of the date
    dayOptional. Specifies the offset from the first day of the week. Default is 1

    Technical Details

    Return Value: Returns a DateTime object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.3: Changed the return value from NULL to DateTime
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Modify the timestamp. Add 15 days: <?php $date=date_create("2013-05-01");date_modify($date,"+15 days");echo date_format($date,"Y-m-d");?> Try it Yourself »

    Definition and Usage

    The date_modify() function modifies the timestamp.

    Syntax

    date_modify(object, modify)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    modifyRequired. Specifies a date/time string

    Technical Details

    Return Value: Returns a DateTime object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.3: Changed the return value from NULL to DateTime
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the timezone offset for Oslo (in Norway, Europe) in seconds from UTC, winter and summer: <?php $winter=date_create("2013-12-31",timezone_open("Europe/Oslo")); $summer=date_create("2013-06-30",timezone_open("Europe/Oslo"));echo date_offset_get($winter) . " seconds.<br>";echo date_offset_get($summer) . " seconds.";?> Try it Yourself »

    Definition and Usage

    The date_offset_get() function returns the timezone offset.

    Syntax

    date_offset_get(object)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()

    Technical Details

    Return Value: Returns the timezone offset in seconds from UTC on success. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return an associative array with detailed information about a specified date, according to the specified format: <?php print_r(date_parse_from_format("mmddyyyy","05122013"));?> Try it Yourself »

    Definition and Usage

    The date_parse_from_format() function returns an associative array with detailed information about a specified date, according to the specified format.

    Syntax

    date_parse_from_format(format, date)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format (a format accepted by date_create_from_format())
    dateRequired. A string that specifies a date

    Technical Details

    Return Value: Returns an associative array containing information about the specified date on success
    PHP Version: 5.3+
    PHP Changelog: PHP 7.2: The [zone] element of the returned array now represents seconds instead of minutes. It also has its sign inverted: -120 is now 7200.
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return an associative array with detailed information about a specified date: <?php print_r(date_parse("2013-05-01 12:30:45.5"));?> Try it Yourself »

    Definition and Usage

    The date_parse() function returns an associative array with detailed information about a specified date.

    Syntax

    date_parse(date)

    Parameter Values

    ParameterDescription
    dateRequired. Specifies a date (in a format accepted by strtotime())

    Technical Details

    Return Value: Returns an associative array containing information about the parsed date on success. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Subtract 40 days from the 15th of March, 2013: <?php $date=date_create("2013-03-15"); date_sub($date,date_interval_create_from_date_string("40 days"));echo date_format($date,"Y-m-d");?> Try it Yourself »

    Definition and Usage

    The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.

    Syntax

    date_sub(object, interval)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    intervalRequired. Specifies a DateInterval object

    Technical Details

    Return Value: Returns a DateTime object on success. FALSE on failure
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return information about sunset/sunrise and twilight begin/end on 1st January, 2013, for latitude 31.7667, longitude 35.2333: <?php $sun_info=date_sun_info(strtotime("2013-01-01"),31.7667,35.2333);foreach ($sun_info as $key=>$val) { echo "$key: " . date("H:i:s",$val) . "<br>"; }?> Try it Yourself »

    Definition and Usage

    The date_sun_info() function returns an array containing information about sunset/sunrise and twilight begin/end, for a specified day and location. Tip: Look at the date_sunrise() function to return the sunrise time for a specified day and location. Tip: Look at the date_sunset() function to return the sunset time for a specified day and location.

    Syntax

    date_sun_info(timestamp, latitude, longitude)

    Parameter Values

    ParameterDescription
    timestampRequired. Specifies a timestamp
    latitudeRequired. Specifies the latitude in degrees
    longitudeRequired. Specifies the longitude in degrees

    Technical Details

    Return Value: Returns an array on success. FALSE on failure
    PHP Version: 5.1.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the sunrise time for Lisbon, Portugal today: <?php // Lisbon, Portugal: // Latitude: 38.4 North, Longitude: 9 West // Zenith ~= 90, offset: +1 GMT echo("Lisbon, Portugal: Date: " . date("D M d Y")); echo("<br>Sunrise time: "); echo(date_sunrise(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1)); ?> Try it Yourself »

    Definition and Usage

    The date_sunrise() function returns the sunrise time for a specified day and location. Tip: Look at the date_sunset() function to return the sunset time for a specified day and location.

    Syntax

    date_sunrise(timestamp, format, latitude, longitude, zenith, gmtoffset)

    Parameter Values

    ParameterDescription
    timestampRequired. Specifies the timestamp of the day from which the sunrise time is taken
    format Optional. Specifies how to return the result:
  • SUNFUNCS_RET_STRING (returns the result as string. e.g. 16:46) (This is default)
  • SUNFUNCS_RET_DOUBLE (returns the result as float. e.g. 16.78243132)
  • SUNFUNCS_RET_TIMESTAMP (returns the result as integer (timestamp). e.g. 1095034606)
  • latitudeOptional. Specifies the latitude of the location. Defaults to North. To specify a value for South, pass in a negative value
    longitudeOptional. Specifies the longitude of the location. Defaults to East. To specify a value for West, pass in a negative value
    zenithOptional. Defaults to date.sunrise_zenith
    gmtoffsetOptional. Specifies the difference between GMT and local time in hours

    Technical Details

    Return Value: Returns the time of the sunrise, in the specified format, on success. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.1: This function now issues E_STRICT and E_NOTICE time zone errors
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the sunset time for Lisbon, Portugal today: <?php // Lisbon, Portugal: // Latitude: 38.4 North, Longitude: 9 West // Zenith ~= 90, offset: +1 GMT echo("Lisbon, Portugal: Date: " . date("D M d Y")); echo("<br>Sunset time: "); echo(date_sunset(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1)); ?> Try it Yourself »

    Definition and Usage

    The date_sunset() function returns the sunset time for a specified day and location. Tip: Look at the date_sunrise() function to return the sunrise time for a specified day and location.

    Syntax

    date_sunset(timestamp, format, latitude, longitude, zenith, gmtoffset)

    Parameter Values

    ParameterDescription
    timestampRequired. Specifies the timestamp of the day from which the sunset time is taken
    format Optional. Specifies how to return the result:
  • SUNFUNCS_RET_STRING (returns the result as string. e.g. 16:46) (This is default)
  • SUNFUNCS_RET_DOUBLE (returns the result as float. e.g. 16.78243132)
  • SUNFUNCS_RET_TIMESTAMP (returns the result as integer (timestamp). e.g. 1095034606)
  • latitudeOptional. Specifies the latitude of the location. Defaults to North. To specify a value for South, pass in a negative value
    longitudeOptional. Specifies the longitude of the location. Defaults to East. To specify a value for West, pass in a negative value
    zenithOptional. Defaults to date.sunset_zenith
    gmtoffsetOptional. Specifies the difference between GMT and local time in hours

    Technical Details

    Return Value: Returns the time of the sunset, in the specified format, on success. FALSE on failure
    PHP Version: 5+
    Changelog: From PHP 5.1.0 this function generates E_STRICT and E_NOTICE time zone errors
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Set the time: <?php $date=date_create("2013-05-01");date_time_set($date,13,24);echo date_format($date,"Y-m-d H:i:s");?> Try it Yourself »

    Definition and Usage

    The date_time_set() function sets the time.

    Syntax

    date_time_set(object, hour, minute, second, microseconds)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()
    hourRequired. Specifies the hour of the time
    minuteRequired. Specifies the minute of the time
    secondOptional. Specifies the second of the time. Default is 0
    microsecondsOptional. Specifies the microsecond of the time. Default is 0

    Technical Details

    Return Value: Returns a DateTime object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 7.1: Added microseconds parameterPHP 5.3: Changed the return value from NULL to DateTime
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the Unix timestamp for today's date and time: <?php $date=date_create();echo date_timestamp_get($date);?> Try it Yourself »

    Definition and Usage

    The date_timestamp_get() function returns the Unix timestamp.

    Syntax

    date_timestamp_get(object)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create()

    Technical Details

    Return Value: Returns the Unix timestamp that represents the date
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Set the date and time based on a Unix timestamp: <?php $date=date_create();date_timestamp_set($date,1371803321);echo date_format($date,"U = Y-m-d H:i:s");?> Try it Yourself »

    Definition and Usage

    The date_timestamp_set() function sets the date and time based on a Unix timestamp.

    Syntax

    date_timestamp_set(object, unixtimestamp)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create(). This function modifies this object
    unixtimestampRequired. Specifies a Unix timestamp representing the date

    Technical Details

    Return Value: Returns the DateTime object for method chaining. FALSE on failure
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the timezone of the given DateTime object: <?php $date=date_create(null,timezone_open("Europe/Paris")); $tz=date_timezone_get($date);echo timezone_name_get($tz);?> Try it Yourself »

    Definition and Usage

    The date_timezone_get() function returns the time zone of the given DateTime object.

    Syntax

    date_timezone_get(object)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create().

    Technical Details

    Return Value: Returns a DateTimeZone object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Set the timezone for the DateTime object: <?php $date=date_create("2013-05-25",timezone_open("Indian/Kerguelen"));echo date_format($date,"Y-m-d H:i:sP");?> Try it Yourself »

    Definition and Usage

    The date_timezone_set() function sets the time zone for the DateTime object.

    Syntax

    date_timezone_set(object, timezone)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTime object returned by date_create(). This function modifies this object
    timezoneRequired. Specifies a DateTimeZone object that represents the desired time zone.Tip: Look at a list of all supported timezones in PHP

    Technical Details

    Return Value: Returns the DateTime object for method chaining. FALSE on failure
    PHP Version: 5.2+
    Changelog: PHP 5.3: Changed the return value from NULL to DateTime (on success)
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Format a local date and time and return the formatted date strings: <?php // Prints the dayecho date("l") . "<br>";// Prints the day, date, month, year, time, AM or PMecho date("l jS \of F Y h:i:s A");?> Try it Yourself »

    Definition and Usage

    The date() function formats a local date and time, and returns the formatted date string.

    Syntax

    date(format, timestamp)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format of the outputted date string. The following characters can be used:
  • d - The day of the month (from 01 to 31)
  • D - A textual representation of a day (three letters)
  • j - The day of the month without leading zeros (1 to 31)
  • l (lowercase 'L') - A full textual representation of a day
  • N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
  • S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
  • w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
  • z - The day of the year (from 0 through 365)
  • W - The ISO-8601 week number of year (weeks starting on Monday)
  • F - A full textual representation of a month (January through December)
  • m - A numeric representation of a month (from 01 to 12)
  • M - A short textual representation of a month (three letters)
  • n - A numeric representation of a month, without leading zeros (1 to 12)
  • t - The number of days in the given month
  • L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
  • o - The ISO-8601 year number
  • Y - A four digit representation of a year
  • y - A two digit representation of a year
  • a - Lowercase am or pm
  • A - Uppercase AM or PM
  • B - Swatch Internet time (000 to 999)
  • g - 12-hour format of an hour (1 to 12)
  • G - 24-hour format of an hour (0 to 23)
  • h - 12-hour format of an hour (01 to 12)
  • H - 24-hour format of an hour (00 to 23)
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds, with leading zeros (00 to 59)
  • u - Microseconds (added in PHP 5.2.2)
  • e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
  • I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
  • O - Difference to Greenwich time (GMT) in hours (Example: +0100)
  • P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
  • T - Timezone abbreviations (Examples: EST, MDT)
  • Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
  • c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
  • r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
  • U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • and the following predefined constants can also be used (available since PHP 5.1.0):
  • DATE_ATOM - Atom (example: 2013-04-12T15:52:01+00:00)
  • DATE_COOKIE - HTTP Cookies (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
  • DATE_RFC822 - RFC 822 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC850 - RFC 850 (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_RFC1036 - RFC 1036 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC1123 - RFC 1123 (example: Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC2822 - RFC 2822 (Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC3339 - Same as DATE_ATOM (since PHP 5.1.3)
  • DATE_RSS - RSS (Fri, 12 Aug 2013 15:52:01 +0000)
  • DATE_W3C - World Wide Web Consortium (example: 2013-04-12T15:52:01+00:00)
  • timestampOptional. Specifies an integer Unix timestamp. Default is the current local time (time())

    Technical Details

    Return Value: Returns a formatted date string on success. FALSE on failure + an E_WARNING
    PHP Version: 4+
    Changelog: PHP 5.1.0: Added E_STRICT and E_NOTICE time zone errors. Valid range of timestamp is now from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. Before version 5.1.0 timestamp was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).PHP 5.1.1: Added constants of standard date/time formats that can be used to specify the format parameter
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return date/time information of the current local date/time: <?php print_r(getdate());?> Try it Yourself »

    Definition and Usage

    The getdate() function returns date/time information of a timestamp or the current local date/time.

    Syntax

    getdate(timestamp)

    Parameter Values

    ParameterDescription
    timestampOptional. Specifies an integer Unix timestamp. Default is the current local time (time())

    Technical Details

    Return Value: Returns an associative array with information related to the timestamp:
  • [seconds] - seconds
  • [minutes] - minutes
  • [hours] - hours
  • [mday] - day of the month
  • [wday] - day of the week (0=Sunday, 1=Monday,...)
  • [mon] - month
  • [year] - year
  • [yday] - day of the year
  • [weekday] - name of the weekday
  • [month] - name of the month
  • [0] - seconds since Unix Epoch
  • PHP Version: 4+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the current time: <?php // Print the array from gettimeofday()print_r(gettimeofday());// Print the float from gettimeofday()echo gettimeofday(true);?> Try it Yourself »

    Definition and Usage

    The gettimeofday() function returns the current time.

    Syntax

    gettimeofday(return_float)

    Parameter Values

    ParameterDescription
    return_floatOptional. When set to TRUE, a float instead of an array is returned. Default is FALSE

    Technical Details

    Return Value: Returns an associative array by default, with the following array keys:
  • [sec] - seconds since the Unix Epoch
  • [usec] - microseconds
  • [minuteswest] - minutes west of Greenwich
  • [dsttime] - type of dst correction
  • If the return_float parameter is set to true, a float is returned
    PHP Version: 4+
    Changelog: PHP 5.1.0: Added the return_float parameter
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Format a GMT/UTC date and time and return the formatted date strings: <?php // Prints the dayecho gmdate("l") . "<br>";// Prints the day, date, month, year, time, AM or PMecho gmdate("l jS \of F Y h:i:s A");?> Try it Yourself »

    Definition and Usage

    The gmdate() function formats a GMT/UTC date and time, and returns the formatted date string.

    Syntax

    gmdate(format, timestamp)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format of the outputted date string. The following characters can be used:
  • d - The day of the month (from 01 to 31)
  • D - A textual representation of a day (three letters)
  • j - The day of the month without leading zeros (1 to 31)
  • l (lowercase 'L') - A full textual representation of a day
  • N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
  • S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
  • w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
  • z - The day of the year (from 0 through 365)
  • W - The ISO-8601 week number of year (weeks starting on Monday)
  • F - A full textual representation of a month (January through December)
  • m - A numeric representation of a month (from 01 to 12)
  • M - A short textual representation of a month (three letters)
  • n - A numeric representation of a month, without leading zeros (1 to 12)
  • t - The number of days in the given month
  • L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
  • o - The ISO-8601 year number
  • Y - A four digit representation of a year
  • y - A two digit representation of a year
  • a - Lowercase am or pm
  • A - Uppercase AM or PM
  • B - Swatch Internet time (000 to 999)
  • g - 12-hour format of an hour (1 to 12)
  • G - 24-hour format of an hour (0 to 23)
  • h - 12-hour format of an hour (01 to 12)
  • H - 24-hour format of an hour (00 to 23)
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds, with leading zeros (00 to 59)
  • u - Microseconds (added in PHP 5.2.2)
  • e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
  • I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
  • O - Difference to Greenwich time (GMT) in hours (Example: +0100)
  • P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
  • T - Timezone abbreviations (Examples: EST, MDT)
  • Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
  • c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
  • r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
  • U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • and the following predefined constants can also be used (available since PHP 5.1.0):
  • DATE_ATOM - Atom (example: 2013-04-12T15:52:01+00:00)
  • DATE_COOKIE - HTTP Cookies (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
  • DATE_RFC822 - RFC 822 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC850 - RFC 850 (example: Friday, 12-Apr-13 15:52:01 UTC)
  • DATE_RFC1036 - RFC 1036 (example: Fri, 12 Apr 13 15:52:01 +0000)
  • DATE_RFC1123 - RFC 1123 (example: Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC2822 - RFC 2822 (Fri, 12 Apr 2013 15:52:01 +0000)
  • DATE_RFC3339 - Same as DATE_ATOM (since PHP 5.1.3)
  • DATE_RSS - RSS (Fri, 12 Aug 2013 15:52:01 +0000)
  • DATE_W3C - World Wide Web Consortium (example: 2013-04-12T15:52:01+00:00)
  • timestampOptional. Specifies an integer Unix timestamp. Default is the current local time (time())

    Technical Details

    Return Value: Returns a formatted date string on success. FALSE on failure + an E_WARNING
    PHP Version: 4+
    PHP Changelog: PHP 5.1: Valid range of timestamp is now from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. Before version 5.1 timestamp was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).PHP 5.1.1: Added the constants of standard date/time formats that can be used to specify the format parameter
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the Unix timestamp for a GMT date. Then use it to find the day of that date: <?php // Prints: October 3, 1975 was on a Fridayecho "Oct 3, 1975 was on a ".date("l", gmmktime(0,0,0,10,3,1975));?> Try it Yourself »

    Definition and Usage

    The gmmktime() function returns the Unix timestamp for a GMT date. Tip: This function is identical to mktime() except the passed parameters represents a GMT date.

    Syntax

    gmmktime(hour, minute, second, month, day, year, is_dst)

    Parameter Values

    ParameterDescription
    hourOptional. Specifies the hour
    minuteOptional. Specifies the minute
    secondOptional. Specifies the second
    monthOptional. Specifies the month
    dayOptional. Specifies the day
    yearOptional. Specifies the year
    is_dstOptional. Parameters always represent a GMT date so is_dst doesn't influence the result. Note: This parameter is removed in PHP 7.0. The new timezone handling features should be used instead

    Technical Details

    Return Value: Returns an integer Unix timestamp
    PHP Version: 4+
    PHP Changelog: PHP 5.1: The is_dst parameter was deprecatedPHP 7.0: The is_dst parameter was removed
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Format GMT/UTC date and time according to locale settings: <?php echo(gmstrftime("%B %d %Y, %X %Z",mktime(20,0,0,12,31,98))."<br>"); setlocale(LC_ALL,"hu_HU.UTF8");echo(gmstrftime("%Y. %B %d. %A. %X %Z"));?> Try it Yourself »

    Definition and Usage

    The gmstrftime() function formats a GMT/UTC time and/or date according to locale settings. Tip: Also look at the strftime() function, which formats a local time and/or date according to locale settings.

    Syntax

    gmstrftime(format, timestamp)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies how to return the result:
  • %a - abbreviated weekday name
  • %A - full weekday name
  • %b - abbreviated month name
  • %B - full month name
  • %c - preferred date and time representation
  • %C - century number (the year divided by 100, range 00 to 99)
  • %d - day of the month (01 to 31)
  • %D - same as %m/%d/%y
  • %e - day of the month (1 to 31)
  • %g - like %G, but without the century
  • %G - 4-digit year corresponding to the ISO week number (see %V).
  • %h - same as %b
  • %H - hour, using a 24-hour clock (00 to 23)
  • %I - hour, using a 12-hour clock (01 to 12)
  • %j - day of the year (001 to 366)
  • %m - month (01 to 12)
  • %M - minute
  • %n - newline character
  • %p - either am or pm according to the given time value
  • %r - time in a.m. and p.m. notation
  • %R - time in 24 hour notation
  • %S - second
  • %t - tab character
  • %T - current time, equal to %H:%M:%S
  • %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
  • %U - week number of the current year, starting with the first Sunday as the first day of the first week
  • %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
  • %W - week number of the current year, starting with the first Monday as the first day of the first week
  • %w - day of the week as a decimal, Sunday=0
  • %x - preferred date representation without the time
  • %X - preferred time representation without the date
  • %y - year without a century (range 00 to 99)
  • %Y - year including the century
  • %Z or %z - time zone or name or abbreviation
  • %% - a literal % character
  • timestampOptional. Specifies a Unix timestamp that represents the date and/or time to be formatted. Default is the current local time (time())

    Technical Details

    Return Value: Returns a string formatted according format using the given timestamp. Month and weekday names and other language-dependent strings respect the current locale set with setlocale()
    PHP Version: 4+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Format a local time/date as integer. Test all the different formats: <?php echo idate("B") . "<br>";echo idate("d") . "<br>";echo idate("h") . "<br>";echo idate("H") . "<br>";echo idate("i") . "<br>";echo idate("I") . "<br>";echo idate("L") . "<br>";echo idate("m") . "<br>";echo idate("s") . "<br>";echo idate("t") . "<br>";echo idate("U") . "<br>";echo idate("w") . "<br>";echo idate("W") . "<br>";echo idate("y") . "<br>";echo idate("Y") . "<br>";echo idate("z") . "<br>";echo idate("Z") . "<br>";?> Try it Yourself »

    Definition and Usage

    The idate() function formats a local time and/or date as integer. Note: The idate() function accepts just one character in the format parameter!

    Syntax

    idate(format, timestamp)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies how to return the result. One of the following characters is allowed:
  • B - Swatch Beat/Internet Time
  • d - Day of the month
  • h - Hour (12 hour format)
  • H - Hour (24 hour format)
  • i - Minutes
  • I - returns 1 if DST (daylight saving time) is activated, 0 otherwise
  • L - returns 1 for leap year, 0 otherwise
  • m - Month number
  • s - Seconds
  • t - Days in current month
  • U - Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • w - Day of the week (Sunday=0)
  • W - ISO-8601 week number of year (week starts on Monday)
  • y - Year (1 or 2 digits)
  • Y - Year (4 digits)
  • z - Day of the year
  • Z - Timezone offset in seconds
  • timestampOptional. Specifies a Unix timestamp that represents the date and/or time to be formatted. Default is the current local time (time())

    Technical Details

    Return Value: Returns an integer formatted according the specified format using the given timestamp
    PHP Version: 5+
    PHP Changelog: PHP 5.1: Now issues E_STRICT and E_NOTICE time zone errors
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Print local time as an indexed and as an associative array: <?php print_r(localtime());echo "<br><br>"; print_r(localtime(time(),true));?> Try it Yourself »

    Definition and Usage

    The localtime() function returns the local time.

    Syntax

    localtime(timestamp, is_assoc)

    Parameter Values

    ParameterDescription
    timestampOptional. Specifies a Unix timestamp that defaults to the current local time, time(), if no timestamp is specified
    is_assocOptional. Specifies whether to return an associative or indexed array. FALSE = the array returned is an indexed array. TRUE = the array returned is an associative array. FALSE is default. The keys of the associative array are:
  • [tm_sec] - seconds
  • [tm_min] - minutes
  • [tm_hour] - hour
  • [tm_mday] - day of the month
  • [tm_mon] - month of the year (January=0)
  • [tm_year] - Years since 1900
  • [tm_wday] - Day of the week (Sunday=0)
  • [tm_yday] - Day of the year
  • [tm_isdst] - Is daylight savings time in effect
  • Technical Details

    Return Value: Returns an array that contains the components of a Unix timestamp
    PHP Version: 4+
    PHP Changelog: PHP 5.1: Now issues E_STRICT and E_NOTICE time zone errors
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the current Unix timestamp with microseconds: <?php echo(microtime());?> Try it Yourself »

    Definition and Usage

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

    Syntax

    microtime(return_float);

    Parameter Values

    ParameterDescription
    return_floatOptional. When set to TRUE it specifies that the function should return a float, instead of a string. Default is FALSE

    Technical Details

    Return Value: Returns the string "microsec sec" by default, where sec is the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and microsec is the microseconds part. If the return_float parameter is set to TRUE, it returns a float representing the current time in seconds since the Unix epoch accurate to the nearest microsecond
    PHP Version: 4+
    PHP Changelog: PHP 5.0: Added the return_float parameter
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the Unix timestamp for a date. Then use it to find the day of that date: <?php // Prints: October 3, 1975 was on a Fridayecho "Oct 3, 1975 was on a ".date("l", mktime(0,0,0,10,3,1975));?> Try it Yourself »

    Definition and Usage

    The gmmktime() function returns the Unix timestamp for a date. Tip: This function is identical to gmmktime() except the passed parameters represents a date (not a GMT date).

    Syntax

    mktime(hour, minute, second, month, day, year, is_dst)

    Parameter Values

    ParameterDescription
    hourOptional. Specifies the hour
    minuteOptional. Specifies the minute
    secondOptional. Specifies the second
    monthOptional. Specifies the month
    dayOptional. Specifies the day
    yearOptional. Specifies the year
    is_dstOptional. Set this parameter to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown. If it's unknown, PHP tries to find out itself (which may cause unexpected results). Note: This parameter is removed in PHP 7.0. The new timezone handling features should be used instead

    Technical Details

    Return Value: Returns an integer Unix timestamp. FALSE on error
    PHP Version: 4+
    PHP Changelog: PHP 7.1: The is_dst parameter is removed.PHP 5.3.0: Throws E_DEPRECATED if the is_dst parameter is used PHP 5.1: The is_dst parameter was deprecated. If mktime() is called with no arguments, it now throws E_STRICT notice. Use the time() function instead.
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Format local date and time according to locale settings: <?php echo(strftime("%B %d %Y, %X %Z",mktime(20,0,0,12,31,98))."<br>"); setlocale(LC_ALL,"hu_HU.UTF8");echo(strftime("%Y. %B %d. %A. %X %Z"));?> Try it Yourself »

    Definition and Usage

    The strftime() function formats a local time and/or date according to locale settings. Tip: Also look at the gmstrftime() function, which formats a GMT/UTC time and/or date according to locale settings.

    Syntax

    strftime(format, timestamp)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies how to return the result:
  • %a - abbreviated weekday name
  • %A - full weekday name
  • %b - abbreviated month name
  • %B - full month name
  • %c - preferred date and time representation
  • %C - century number (the year divided by 100, range 00 to 99)
  • %d - day of the month (01 to 31)
  • %D - same as %m/%d/%y
  • %e - day of the month (1 to 31)
  • %g - like %G, but without the century
  • %G - 4-digit year corresponding to the ISO week number (see %V).
  • %h - same as %b
  • %H - hour, using a 24-hour clock (00 to 23)
  • %I - hour, using a 12-hour clock (01 to 12)
  • %j - day of the year (001 to 366)
  • %m - month (01 to 12)
  • %M - minute
  • %n - newline character
  • %p - either am or pm according to the given time value
  • %r - time in a.m. and p.m. notation
  • %R - time in 24 hour notation
  • %S - second
  • %t - tab character
  • %T - current time, equal to %H:%M:%S
  • %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
  • %U - week number of the current year, starting with the first Sunday as the first day of the first week
  • %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
  • %W - week number of the current year, starting with the first Monday as the first day of the first week
  • %w - day of the week as a decimal, Sunday=0
  • %x - preferred date representation without the time
  • %X - preferred time representation without the date
  • %y - year without a century (range 00 to 99)
  • %Y - year including the century
  • %Z or %z - time zone or name or abbreviation
  • %% - a literal % character
  • timestampOptional. Specifies a Unix timestamp that represents the date and/or time to be formatted. Default is the current local time (time())

    Technical Details

    Return Value: Returns a string formatted according format using the given timestamp. Month and weekday names and other language-dependent strings respect the current locale set with setlocale()
    PHP Version: 4+
    PHP Changelog: PHP 5.1: Now issues E_STRICT and E_NOTICE time zone errors
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Parse a time/date generated with strftime(): <?php $format="%d/%m/%Y %H:%M:%S"; $strf=strftime($format); echo("$strf"); print_r(strptime($strf,$format));?>

    Definition and Usage

    The strptime() function parses a time/date generated with strftime(). Note: This function is not implemented on Windows platforms!

    Syntax

    strptime(date, format)

    Parameter Values

    ParameterDescription
    dateRequired. The string to parse (e.g. returned from strftime())
    formatRequired. Specifies the format used in the date:
  • %a - abbreviated weekday name
  • %A - full weekday name
  • %b - abbreviated month name
  • %B - full month name
  • %c - preferred date and time representation
  • %C - century number (the year divided by 100, range 00 to 99)
  • %d - day of the month (01 to 31)
  • %D - same as %m/%d/%y
  • %e - day of the month (1 to 31)
  • %g - like %G, but without the century
  • %G - 4-digit year corresponding to the ISO week number (see %V).
  • %h - same as %b
  • %H - hour, using a 24-hour clock (00 to 23)
  • %I - hour, using a 12-hour clock (01 to 12)
  • %j - day of the year (001 to 366)
  • %m - month (01 to 12)
  • %M - minute
  • %n - newline character
  • %p - either am or pm according to the given time value
  • %r - time in a.m. and p.m. notation
  • %R - time in 24 hour notation
  • %S - second
  • %t - tab character
  • %T - current time, equal to %H:%M:%S
  • %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
  • %U - week number of the current year, starting with the first Sunday as the first day of the first week
  • %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
  • %W - week number of the current year, starting with the first Monday as the first day of the first week
  • %w - day of the week as a decimal, Sunday=0
  • %x - preferred date representation without the time
  • %X - preferred time representation without the date
  • %y - year without a century (range 00 to 99)
  • %Y - year including the century
  • %Z or %z - time zone or name or abbreviation
  • %% - a literal % character
  • Technical Details

    Return Value: This function returns an array with the date parsed on success. FALSE on failure. The meaning of the returning array keys are:
  • [tm_sec] - seconds (0-61)
  • [tm_min] - minutes (0-59)
  • [tm_hour] - hour (0-23)
  • [tm_mday] - day of the month (1-31)
  • [tm_mon] - months since January (0-11)
  • [tm_year] - years since 1900
  • [tm_wday] - days since Sunday (0-6)
  • [tm_yday] - days since January 1 (0-365)
  • [unparsed] - the date part which was not recognized using the specified format, if any
  • PHP Version: 5.1+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Parse English textual datetimes into Unix timestamps: <?php echo(strtotime("now") . "<br>"); echo(strtotime("3 October 2005") . "<br>"); echo(strtotime("+5 hours") . "<br>"); echo(strtotime("+1 week") . "<br>"); echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>"); echo(strtotime("next Monday") . "<br>"); echo(strtotime("last Sunday"));?> Try it Yourself »

    Definition and Usage

    The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000. Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible.

    Syntax

    strtotime(time, now);

    Parameter Values

    ParameterDescription
    timeRequired. Specifies a date/time string
    nowOptional. Specifies the timestamp used as a base for the calculation of relative dates

    Technical Details

    Return Value: Returns a timestamp on success. FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 5.3.0: Relative time formats such as this week, previous week, last week, and next week now interprets a week period of Monday through Sunday, rather then a 7-day period relative to the current date/timePHP 5.3.0: Now 24:00 is a valid formatPHP 5.2.7: In earlier versions, if requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month it would incorrectly add one week to the returned timestamp. This has been corrected nowPHP 5.1.0: Returns FALSE on failure (earlier versions returns -1), and issues E_STRICT and E_NOTICE time zone errorsPHP 5.0.2: Now correctly computes "now" and other relative times from current time, not from today's midnight PHP 5.0.0: Allows microseconds (but they are ignored)
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the current time as a Unix timestamp, then format it to a date: <?php $t=time(); echo($t . "<br>"); echo(date("Y-m-d",$t));?> Try it Yourself »

    Definition and Usage

    The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

    Syntax

    time()

    Technical Details

    Return Value: Returns an integer containing the current time as a Unix timestamp
    PHP Version: 4+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Print dst, offset, and timezone name for the "act" timezone: <?php $tzlist = DateTimeZone::listAbbreviations();print_r($tzlist["acst"]);?> Try it Yourself »

    Definition and Usage

    The timezone_abbreviations_list() returns an associative array containing dst, offset, and the timezone name.

    Syntax

    timezone_abbreviations_list()

    Technical Details

    Return Value: Returns an associative array on success. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Print all timezones in Africa: <?php print_r(timezone_identifiers_list(1));?> Try it Yourself »

    Definition and Usage

    The timezone_identifiers_list() returns an indexed array containing all timezone identifiers.

    Syntax

    timezone_identifiers_list(what, country)

    Parameter Values

    ParameterDescription
    whatOptional. Specifies a DateTimeZone class constant1 = AFRICA2 = AMERICA4 = ANTARCTICA8 = ARCTIC16 = ASIA32 = ATLANTIC 64 = AUSTRALIA128 = EUROPE256 = INDIAN512 = PACIFIC1024 = UTC2047 = ALL4095 = ALL_WITH_BC4096 = PER_COUNTRY
    countryOptional. Specifies a two-letter ISO 3166-1 compatible country code

    Technical Details

    Return Value: Returns an indexed array on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.3: The optional what and country parameters were added
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return location information for the given timezone: <?php $tz=timezone_open("Asia/Taipei"); print_r(timezone_location_get($tz));?> Try it Yourself »

    Definition and Usage

    The timezone_location_get() returns location information for the given timezone.

    Syntax

    timezone_location_get(object)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTimeZone object returned by timezone_open()

    Technical Details

    Return Value: Returns an array that contains location information for the timezone
    PHP Version: 5.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the timezone name from abbreviation: <?php echo timezone_name_from_abbr("EST") . "<br>";echo timezone_name_from_abbr(",7200,0);?> Try it Yourself »

    Definition and Usage

    The timezone_name_from_abbr() returns the timezone name from abbreviation.

    Syntax

    timezone_name_from_abbr(abbr, gmtoffset, isdst)

    Parameter Values

    ParameterDescription
    abbrRequired. Specifies the timezone abbreviation
    gmtoffsetOptional. Specifies the offset from GMT in seconds. Default is -1, which means that first found timezone corresponding to abbr is returned. Otherwise exact offset is searched. If not found, the first timezone with any offset is returned
    isdst Optional. Specifies daylight saving time indicator.
  • -1 = Default. Whether the timezone has daylight saving or not is not taken into consideration when searching
  • 1 = Means that the gmtoffset is an offset with daylight saving in effect
  • 0 = Means that the gmtoffset is an offset without daylight saving in effect
  • Technical Details

    Return Value: Returns the timezone name on success. FALSE on failure
    PHP Version: 5.1.3+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the name of the timezone: <?php $tz=timezone_open("Europe/Paris"); echo timezone_name_get($tz);?> Try it Yourself »

    Definition and Usage

    The timezone_name_get() returns the name of the timezone.

    Syntax

    timezone_name_get(object)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTimeZone object

    Technical Details

    Return Value: Returns a timezone name from the list of timezones
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the timezone offset from GMT: <?php $tz=timezone_open("Asia/Taipei"); $dateTimeOslo=date_create("now",timezone_open("Europe/Oslo"));echo timezone_offset_get($tz,$dateTimeOslo);?> Try it Yourself »

    Definition and Usage

    The timezone_offset_get() returns the timezone offset from GMT.

    Syntax

    timezone_offset_get(object, datetime)

    Parameter Values

    ParameterDescription
    objectRequired. Specifies a DateTimeZone object returned by timezone_open()
    datetimeRequired. Specifies a date/time to compute the offset from

    Technical Details

    Return Value: Returns the timezone offset in seconds on success. FALSE on failure
    PHP Version: 5.2+
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Create a new DateTimeZone object, then return the name of the timezone: <?php $tz=timezone_open("Europe/Paris"); echo timezone_name_get($tz);?> Try it Yourself »

    Definition and Usage

    The timezone_open() creates a new DateTimeZone object.

    Syntax

    The two functions below are equivalent and any of the functions can be used as shown in the example above. Procedural style: timezone_open(timezone) Object oriented style: DateTimeZone::__construct(timezone)

    Parameter Values

    ParameterDescription
    timezoneRequired. Specifies a timezoneTip: Look at a list of all supported timezones in PHP

    Technical Details

    Return Value: Returns the DateTimeZone object on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.5.1: The timezone parameter accepts offset values
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return a transition for a timezone: <?php $timezone = new DateTimeZone("Europe/Paris"); // Procedural styleprint_r(reset(timezone_transitions_get($timezone))); echo "<br><br>"// Object oriented styleprint_r(reset($timezone->getTransitions())); ?> Try it Yourself »

    Definition and Usage

    The timezone_transitions_get() returns all transitions for the timezone.

    Syntax

    The two functions below are equivalent and any of the functions can be used as shown in the example above. Procedural style: timezone_transitions_get(object, timestamp_start, timestamp_end) Object oriented style: DateTimeZone::getTransitions(timestamp_start, timestamp_end)

    Parameter Values

    ParameterDescription
    objectRequired (for procedural style). Specifies a DateTimeZone object
    timestamp_startOptional. Begin timestamp
    timestamp_endOptional. End timestamp

    Technical Details

    Return Value: A numerically indexed array containing associative array with all transitions on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.3: Added timestamp_begin and timestamp_end parameters
    PHP Date/Time Reference PHP Date/Time Reference

    Example

    Return the version of the timezonedb: <?php echo timezone_version_get();?> Try it Yourself »

    Definition and Usage

    The timezone_version_get() function returns the version of the timezonedb.

    Syntax

    timezone_version_get()

    Technical Details

    Return Value: Returns the version of the timezonedb as a string
    PHP Version: 5.3+
    PHP Date/Time Reference

    Directory Introduction

    The directory functions allow you to retrieve information about directories and their contents.

    Installation

    The PHP directory functions are part of the PHP core. No installation is required to use these functions.

    Directory Functions

    FunctionDescription
    chdir()Changes the current directory
    chroot()Changes the root directory
    closedir()Closes a directory handle
    dir()Returns an instance of the Directory class
    getcwd()Returns the current working directory
    opendir()Opens a directory handle
    readdir()Returns an entry from a directory handle
    rewinddir()Resets a directory handle
    scandir()Returns an array of files and directories of a specified directory
    PHP Directory Reference

    Example

    Change the current directory: <?php// Get current directory echo getcwd() . "<br>";// Change directory chdir("images");// Get current directory echo getcwd(); ?> Result: /home/php/home/php/images

    Definition and Usage

    The chdir() function changes the current directory.

    Syntax

    chdir(directory)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the new current directory

    Technical Details

    Return Value: TRUE on success. FALSE on failure. Throws an error of level E_WARNING on failure
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    Change the root directory: <?php// Change root directory chroot("/path/to/chroot/");// Get current directory echo getcwd();?> Result: /

    Definition and Usage

    The chroot() function changes the root directory of the current process to directory, and changes the current working directory to "/". Note: This function requires root privileges, and is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Note: This function is not implemented on Windows platforms.

    Syntax

    chroot(directory)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the path to change the root directory to

    Technical Details

    Return Value: TRUE on success. FALSE on failure.
    PHP Version: 4.0.5+
    PHP Directory Reference PHP Directory Reference

    Example

    Open a directory, read its contents, then close: <?php$dir = "/images/";// Open a directory, and read its contentsif (is_dir($dir)){ if ($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } closedir($dh); }}?> Result: filename: cat.gif filename: dog.gif filename: horse.gif

    Definition and Usage

    The closedir() function closes a directory handle.

    Syntax

    closedir(dir)

    Parameter Values

    ParameterDescription
    dirOptional. Specifies the directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed

    Technical Details

    Return Value: -
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    Use the dir() function: <?php $d = dir(getcwd());echo "Handle: " . $d->handle . "<br>"; echo "Path: " . $d->path . "<br>";while (($file = $d->read()) !== false){ echo "filename: " . $file . "<br>"; } $d->close(); ?> Result: Handle: Resource id #2Path: /etc/phpfilename: .filename: .. filename: ajax.giffilename: books.xmlfilename: cdcatalog.xml filename: cd_catalog.xmlfilename: default.aspfilename: demo_array.aspfilename: demo_array.htm... ......

    Definition and Usage

    The dir() function returns an instance of the Directory class. This function is used to read a directory, which includes the following:
  • The given directory is opened
  • The two properties handle and path of dir() are available
  • Both handle and path properties have three methods: read(), rewind(), and close()
  • Syntax

    dir(directory, context)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the directory to open
    contextOptional.

    Technical Details

    Return Value: An instance of the Directory class. FALSE on failure
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    Get the current working directory: <?phpecho getcwd();?> Result: /home/php

    Definition and Usage

    The getcwd() function returns the current working directory.

    Syntax

    getcwd()

    Technical Details

    Return Value: The current working directory on success, FALSE on failure.
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    Open a directory, read its contents, then close: <?php$dir = "/images/";// Open a directory, and read its contentsif (is_dir($dir)){ if ($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } closedir($dh); }}?> Result: filename: cat.gif filename: dog.gif filename: horse.gif

    Definition and Usage

    The opendir() function opens a directory handle.

    Syntax

    opendir(path, context)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the directory path to be opened
    contextOptional. Specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: Returns the directory handle resource on success. FALSE on failure. Throws an error of level E_WARNING if path is not a valid directory, or if the directory cannot be opened due to permission restrictions or filesysytem errors. You can hide the error output of opendir() by adding '@' to the front of the function name
    PHP Version: 4.0+
    PHP Changelog: PHP 5.0: The path parameter now supports the ftp:// URL wrapper
    PHP Directory Reference PHP Directory Reference

    Example

    List all entries in the images directory, then close: <?php$dir = "/images/";// Open a directory, and read its contentsif (is_dir($dir)){ if ($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } closedir($dh); }}?> Result: filename: cat.gif filename: dog.gif filename: horse.gif

    Definition and Usage

    The readdir() function returns the name of the next entry in a directory.

    Syntax

    readdir(dir)

    Parameter Values

    ParameterDescription
    dirOptional. Specifies the directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed

    Technical Details

    Return Value: The entry name (filename) on success, FALSE on failure
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    Open a directory, list its files, reset directory handle, list its files once again, then close: <?php$dir = "/images/";// Open a directory, and read its contentsif (is_dir($dir)){ if ($dh = opendir($dir)){ // List files in images directory while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } rewinddir(); // List once again files in images directory while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } closedir($dh); }}?> Result: filename: cat.gif filename: dog.gif filename: horse.giffilename: cat.gif filename: dog.gif filename: horse.gif

    Definition and Usage

    The rewinddir() function resets the directory handle created by opendir().

    Syntax

    rewinddir(dir)

    Parameter Values

    ParameterDescription
    dirOptional. Specifies the directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed

    Technical Details

    Return Value: NULL on success, FALSE on failure
    PHP Version: 4.0+
    PHP Directory Reference PHP Directory Reference

    Example

    List files and directories inside the images directory: <?php$dir = "/images/";// Sort in ascending order - this is default$a = scandir($dir);// Sort in descending order$b = scandir($dir,1);print_r($a);print_r($b);?> Result: Array([0] => .[1] => ..[2] => cat.gif[3] => dog.gif [4] => horse.gif[5] => myimages)Array([0] => myimages[1] => horse.gif[2] => dog.gif[3] => cat.gif[4] => ..[5] => .)

    Definition and Usage

    The scandir() function returns an array of files and directories of the specified directory.

    Syntax

    scandir(directory, order, context)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the directory to be scanned
    orderOptional. Specifies the sorting order. Default sort order is alphabetical in ascending order (0). Set to SCANDIR_SORT_DESCENDING or 1 to sort in alphabetical descending order, or SCANDIR_SORT_NONE to return the result unsorted
    contextOptional. Specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: An array of files and directories on success, FALSE on failure. Throws an E_WARNING if directory is not a directory
    PHP Version: 5.0+
    PHP Changelog: PHP 5.4: The order constants were added
    PHP Directory Reference

    Error Introduction

    The error functions are used to deal with error handling and logging. The error functions allow us to define own error handling rules, and modify the way the errors can be logged. The logging functions allow us to send messages directly to other machines, emails, or system logs. The error reporting functions allow us to customize what level and kind of error feedback is given.

    Installation

    The PHP error functions are part of the PHP core. No installation is required to use these functions.

    Runtime Configuration

    The behavior of the error functions is affected by settings in php.ini. Errors and logging configuration options:
    NameDefaultDescriptionChangeable
    error_reportingNULLSets the error reporting level (either an integer or named constants)PHP_INI_ALL
    display_errors"1"Specifies whether errors should be printed to the screen, or if they should be hidden from the user.Note: This feature should never be used on production systems (only to support your development)PHP_INI_ALL
    display_startup_errors"0"Even when display_errors is on, errors that occur during PHP's startup sequence are not displayedNote: It is strongly recommended to keep display_startup_errors off, except for debuggingPHP_INI_ALL
    log_errors"0"Defines whether script error messages should be logged to the server's error log or error_log. Note: It is strongly advised to use error logging instead of error displaying on production web sitesPHP_INI_ALL
    log_errors_max_len"1024"Sets the maximum length of log_errors in bytes. The value "0" can be used to not apply any maximum length at all. This length is applied to logged errors, displayed errors, and also to $php_errormsg (available since PHP 4.3)PHP_INI_ALL
    ignore_repeated_errors"0"Specifies whether to log repeated error messages. When set to "1" it will not log errors with repeated errors from the same file on the same line (available since PHP 4.3)PHP_INI_ALL
    ignore_repeated_source"0"Specifies whether to log repeated error messages. When set to "1" it will not log errors with repeated errors from different files or source lines (available since PHP 4.3)PHP_INI_ALL
    report_memleaks"1"If set to "1" (the default), this parameter will show a report of memory leaks detected by the Zend memory manager (available since PHP 4.3)PHP_INI_ALL
    track_errors"0"If set to "1", the last error message will always be present in the variable $php_errormsgPHP_INI_ALL
    html_errors"1"Turns off HTML tags in error messagesPHP_INI_ALLPHP_INI_SYSTEM in PHP <= 4.2.3.
    xmlrpc_errors"0"Turns off normal error reporting and formats errors as XML-RPC error message (available since PHP 4.1)PHP_INI_SYSTEM
    xmlrpc_error_number"0"Used as the value of the XML-RPC faultCode element (available since PHP 4.1)PHP_INI_ALL
    docref_root"(available since PHP 4.3)PHP_INI_ALL
    docref_ext"(available since PHP 4.3.2)PHP_INI_ALL
    error_prepend_stringNULLSpecifies a string to output before an error messagePHP_INI_ALL
    error_append_stringNULLSpecifies a string to output after an error messagePHP_INI_ALL
    error_logNULLSpecifies the name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger insteadPHP_INI_ALL

    Error and Logging Functions

    FunctionDescription
    debug_backtrace()Generates a backtrace
    debug_print_backtrace()Prints a backtrace
    error_clear_last()Clears the last error
    error_get_last()Returns the last error that occurred
    error_log()Sends an error message to a log, to a file, or to a mail account
    error_reporting()Specifies which errors are reported
    restore_error_handler()Restores the previous error handler
    restore_exception_handler()Restores the previous exception handler
    set_error_handler()Sets a user-defined error handler function
    set_exception_handler()Sets a user-defined exception handler function
    trigger_error()Creates a user-level error message
    user_error()Alias of trigger_error()

    Predefined Error and Logging Constants

    ValueConstantDescription
    1E_ERRORFatal run-time errors. Errors that cannot be recovered from. Execution of the script is halted
    2E_WARNINGRun-time warnings (non-fatal errors). Execution of the script is not halted
    4E_PARSECompile-time parse errors. Parse errors should only be generated by the parser
    8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally
    16E_CORE_ERRORFatal errors at PHP startup. This is like E_ERROR, except it is generated by the core of PHP
    32E_CORE_WARNINGNon-fatal errors at PHP startup. This is like E_WARNING, except it is generated by the core of PHP
    64E_COMPILE_ERRORFatal compile-time errors. This is like E_ERROR, except it is generated by the Zend Scripting Engine
    128E_COMPILE_WARNINGNon-fatal compile-time errors. This is like E_WARNING, except it is generated by the Zend Scripting Engine
    256E_USER_ERRORFatal user-generated error. This is like E_ERROR, except it is generated in PHP code by using the PHP function trigger_error()
    512E_USER_WARNINGNon-fatal user-generated warning. This is like E_WARNING, except it is generated in PHP code by using the PHP function trigger_error()
    1024E_USER_NOTICEUser-generated notice. This is like E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error()
    2048E_STRICTEnable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code (Since PHP 5 but not included in E_ALL until PHP 5.4)
    4096E_RECOVERABLE_ERRORCatchable fatal error. Indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle, the application aborts as it was an E_ERROR (Since PHP 5.2)
    8192E_DEPRECATEDRun-time notices. Enable this to receive warnings about code that will not work in future versions (Since PHP 5.3)
    16384E_USER_DEPRECATEDUser-generated warning message. This is like E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error() (Since PHP 5.3)
    32767E_ALLEnable all PHP errors and warnings (except E_STRICT in versions < 5.4)
    PHP Error Reference

    Example

    Generate a PHP backtrace: <?php function a($txt) { b("Glenn"); } function b($txt) { c("Cleveland");} function c($txt) { var_dump(debug_backtrace()); } a("Peter"); ?> Try it Yourself »

    Definition and Usage

    The debug_backtrace() function generates a PHP backtrace. This function displays data from the code that led up to the debug_backtrace() function. Returns an array of associative arrays. The possible returned elements are:
    NameType Description
    functionstringThe current function name
    lineintegerThe current line number
    filestringThe current file name
    classstringThe current class name
    objectobjectThe current object
    typestringThe current call type. Possible calls:
  • Returns: "->" - Method call
  • Returns: "::" - Static method call
  • Returns nothing - Function call
  • argsarrayIf inside a function, it lists the functions arguments. If inside an included file, it lists the included file names

    Syntax

    debug_backtrace(options, limit);

    Parameter Values

    ParameterDescription
    optionsOptional. Specifies a bitmask for the following options:DEBUG_BACKTRACE_PROVIDE_OBJECT (Whether or not to populate the "object" indexDEBUG_BACKTRACE_IGNORE_ARGS (Whether or not to omit the "args" index, and all the function/method arguments, to save memory)
    limitOptional. Limits the number of stack frames printed. By default (limit=0) it prints all stack frames

    Technical Details

    Return Value: An array of associative arrays
    PHP Version: 4.3+
    PHP Changelog: PHP 5.4: The optional parameter limit was addedPHP 5.3.6: The parameter provide_object was changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is addedPHP 5.2.5: The optional parameter provide_object was addedPHP 5.1.1: Added the current object as a possible return element
    PHP Error Reference PHP Error Reference

    Example

    Print a PHP backtrace: <?php function a($txt) { b("Glenn"); } function b($txt) { c("Cleveland");} function c($txt) { debug_print_backtrace(); } a("Peter"); ?> Try it Yourself »

    Definition and Usage

    The debug_print_backtrace() function prints a PHP backtrace. This function displays data from the code that led up to the debug_print_backtrace() function.

    Syntax

    debug_print_backtrace(options, limit);

    Parameter Values

    ParameterDescription
    optionsOptional. Specifies a bitmask for the following option: DEBUG_BACKTRACE_IGNORE_ARGS (Whether or not to omit the "args" index, and all the function/method arguments, to save memory)
    limitOptional. Limits the number of stack frames printed. By default (limit=0) it prints all stack frames

    Technical Details

    Return Value: None
    PHP Version: 5.0+
    PHP Changelog: PHP 5.4: The optional parameter limit was addedPHP 5.3.6: The optional parameter options was added
    PHP Error Reference PHP Error Reference

    Example

    Return the last error that occurred: <?php echo $test; print_r(error_get_last()); ?> Try it Yourself »

    Definition and Usage

    The error_get_last() function returns the last error that occurred (as an associative array). The associative array contains four keys:
  • [type] - Describes the error type
  • [message] - Describes the error message
  • [file] - Describes the file where the error occurred
  • [line] - Describes the line where the error occurred
  • Syntax

    error_get_last();

    Technical Details

    Return Value: Returns an associative array describing the last error with keys: type, message, file, and line. Returns NULL if no error has occurred yet
    PHP Version: 5.2+
    PHP Error Reference PHP Error Reference

    Example

    Send error messages to the web server's error log and to a mail account: <?php // Send error message to the server log if error connecting to the databaseif (!mysqli_connect("localhost","bad_user","bad_password","my_db")) { error_log("Failed to connect to database!", 0);}// Send email to administrator if we run out of FOOif (!($foo = allocate_new_foo())) { error_log("Oh no! We are out of FOOs!", 1, "admin@example.com");}?>

    Definition and Usage

    The error_log() function sends an error message to a log, to a file, or to a mail account.

    Syntax

    error_log(message, type, destination, headers);

    Parameter Values

    ParameterDescription
    messageRequired. Specifies the error message to log
    typeOptional. Specifies where the error message should go. Possible values:
  • 0 - Default. Message is sent to PHP's system logger, using the OS' system logging mechanism or a file, depending on what the error_log configuration is set to in php.ini
  • 1 - Message is sent by email to the address in the destination parameter
  • 2 - No longer in use (only available in PHP 3)
  • 3 - Message is appended to the file specified in destination
  • 4 - Message is sent directly to the SAPI logging handler
  • destinationOptional. Specifies the destination of the error message. This value depends on the value of the type parameter
    headersOptional. Only used if the type parameter is set to 1. Specifies additional headers, like From, Cc, and Bcc. Multiple headers should be separated with a CRLF (\r\n)

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    Binary Safe: No
    PHP Changelog: PHP 5.2.7: The value of 4 was added to the type parameter
    PHP Error Reference PHP Error Reference

    Example

    Specify different error level reporting: <?php // Turn off error reporting error_reporting(0); // Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Report all errors error_reporting(E_ALL);// Same as error_reporting(E_ALL);ini_set("error_reporting", E_ALL);// Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); ?>

    Definition and Usage

    The error_reporting() function specifies which errors are reported. PHP has many levels of errors, and using this function sets that level for the current script.

    Syntax

    error_reporting(level);

    Parameter Values

    ParameterDescription
    levelOptional. Specifies the error-report level for the current script. Error numbers and named constants are accepted. Note: Named constants are recommended to ensure compatibility for future PHP versions

    Technical Details

    Return Value: Returns the old error reporting level or the current error reporting level if no level parameter is given
    PHP Version: 4.0+
    PHP Changelog: PHP 5.4: E_STRICT is now a part of E_ALL.PHP 5.3: New: E_DEPRECATED and E_USER_DEPRECATED.PHP 5.2: New: E_RECOVERABLE_ERROR.PHP 5.0: New: E_STRICT.
    PHP Error Reference PHP Error Reference

    Example

    Restore the previous error handler after changing it with the set_error_handler() function: <?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"); }?> Try it Yourself »

    Definition and Usage

    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. Tip: The previous error handler could be the built-in error handler or a user-defined error handler function.

    Syntax

    restore_error_handler();

    Technical Details

    Return Value: Always TRUE
    PHP Version: 4.0.1+
    PHP Error Reference PHP Error Reference

    Example

    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 exceptionthrow new Exception("This triggers the first exception handler..."); ?> Try it Yourself »

    Definition and Usage

    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. Tip: The previous exception handler could be the built-in exception handler or a user-defined exception handler function.

    Syntax

    restore_exception_handler();

    Technical Details

    Return Value: Always TRUE
    PHP Version: 5.0+
    PHP Error Reference PHP Error Reference

    Example

    Set a user-defined error handler function with the set_error_handler() function, and trigger an error (with trigger_error()): <?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"); } ?> Try it Yourself »

    Definition and Usage

    The set_error_handler() function sets a user-defined error handler function. Note: The standard PHP error handler is completely bypassed if this function is used, and the user-defined error handler must terminate the script, die(), if necessary. Note: If errors occur before the script is executed the custom error handler cannot be used since it is not registered at that time.

    Syntax

    set_error_handler(errorhandler, E_ALL | E_STRICT)

    Parameter Values

    ParameterDescription
    errorhandlerRequired. Specifies the name of the function to be run at errors
    E_ALL|E_STRICTOptional. Specifies on which error report level the user-defined error will be shown. Default is "E_ALL"

    Technical Details

    Return Value: A string that contains the previously defined error handler
    PHP Version: 4.0.1+
    PHP Changelog: PHP 5.5: The parameter errorhandler now accepts NULLPHP 5.2: The error handler must return FALSE to populate $php_errormsg
    PHP Error Reference PHP Error Reference

    Example

    Set a user-defined exception handler function: <?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 exceptionthrow new Exception("Uncaught exception occurred!"); ?> Try it Yourself »

    Definition and Usage

    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);

    Parameter Values

    ParameterDescription
    exceptionhandlerRequired. Specifies the name of the function to be run when an uncaught exception occurs. NULL can be passed instead, to reset this handler to its default state

    Technical Details

    Return Value: A string that contains the previously defined exception handler, or NULL on error or if no previous handler was defined
    PHP Version: 5.0+
    PHP Changelog: Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5
    PHP Error Reference PHP Error Reference

    Example

    If $usernum > 10, trigger an error: <?php if ($usernum>10) { trigger_error("Number cannot be larger than 10"); } ?> Try it Yourself »

    Definition and Usage

    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 the set_error_handler() function.

    Syntax

    trigger_error(message, type)

    Parameter Values

    ParameterDescription
    messageRequired. Specifies the error message for this error. Max 1024 bytes in length
    typeOptional. Specifies the error type for this error. Possible values:
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE (this is default)
  • Technical Details

    Return Value: FALSE if wrong error type is specified, TRUE otherwise
    PHP Version: 4.0.1+
    PHP Error Reference

    Filesystem Introduction

    The filesystem functions allow you to access and manipulate the filesystem.

    Installation

    The filesystem functions are part of the PHP core. There is no installation needed to use these functions.

    Unix / Windows Compatibility

    When specifying a path on Unix platforms, a forward slash (/) is used as directory separator. On Windows platforms, both forward slash (/) and backslash (\) can be used.

    Runtime Configuration

    The behavior of the filesystem functions is affected by settings in php.ini.
    NameDefaultDescriptionChangeable
    allow_url_fopen"1"Allows fopen()-type functions to work with URLsPHP_INI_SYSTEM
    allow_url_include"0"(available since PHP 5.2)PHP_INI_SYSTEM
    user_agentNULLDefines the user agent for PHP to send (available since PHP 4.3)PHP_INI_ALL
    default_socket_timeout"60"Sets the default timeout, in seconds, for socket based streams (available since PHP 4.3) PHP_INI_ALL
    from"Defines the email address to be used on unauthenticated FTP connections and in the From header for HTTP connections when using ftp and http wrappersPHP_INI_ALL
    auto_detect_line_endings"0"When set to "1", PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Mac line-ending characters (available since PHP 4.3)PHP_INI_ALL
    sys_temp_dir"(available since PHP 5.5)PHP_INI_SYSTEM

    Filesystem Functions

    FunctionDescription
    basename()Returns the filename component of a path
    chgrp()Changes the file group
    chmod()Changes the file mode
    chown()Changes the file owner
    clearstatcache()Clears the file status cache
    copy()Copies a file
    delete()See unlink()
    dirname()Returns the directory name component of a path
    disk_free_space()Returns the free space of a filesystem or disk
    disk_total_space()Returns the total size of a filesystem or disk
    diskfreespace()Alias of disk_free_space()
    fclose()Closes an open file
    feof()Checks if the "end-of-file" (EOF) has been reached for an open file
    fflush()Flushes buffered output to an open file
    fgetc()Returns a single character from an open file
    fgetcsv()Returns a line from an open CSV file
    fgets()Returns a line from an open file
    fgetss()Deprecated from PHP 7.3. Returns a line from an open file - stripped from HTML and PHP tags
    file()Reads a file into an array
    file_exists()Checks whether or not a file or directory exists
    file_get_contents()Reads a file into a string
    file_put_contents()Writes data to a file
    fileatime()Returns the last access time of a file
    filectime()Returns the last change time of a file
    filegroup()Returns the group ID of a file
    fileinode()Returns the inode number of a file
    filemtime()Returns the last modification time of a file
    fileowner()Returns the user ID (owner) of a file
    fileperms()Returns the file's permissions
    filesize()Returns the file size
    filetype()Returns the file type
    flock()Locks or releases a file
    fnmatch()Matches a filename or string against a specified pattern
    fopen()Opens a file or URL
    fpassthru()Reads from the current position in a file - until EOF, and writes the result to the output buffer
    fputcsv()Formats a line as CSV and writes it to an open file
    fputs()Alias of fwrite()
    fread()Reads from an open file (binary-safe)
    fscanf()Parses input from an open file according to a specified format
    fseek()Seeks in an open file
    fstat()Returns information about an open file
    ftell()Returns the current position in an open file
    ftruncate()Truncates an open file to a specified length
    fwrite()Writes to an open file (binary-safe)
    glob()Returns an array of filenames / directories matching a specified pattern
    is_dir()Checks whether a file is a directory
    is_executable()Checks whether a file is executable
    is_file()Checks whether a file is a regular file
    is_link()Checks whether a file is a link
    is_readable()Checks whether a file is readable
    is_uploaded_file()Checks whether a file was uploaded via HTTP POST
    is_writable()Checks whether a file is writable
    is_writeable()Alias of is_writable()
    lchgrp()Changes the group ownership of a symbolic link
    lchown()Changes the user ownership of a symbolic link
    link()Creates a hard link
    linkinfo()Returns information about a hard link
    lstat()Returns information about a file or symbolic link
    mkdir()Creates a directory
    move_uploaded_file()Moves an uploaded file to a new location
    parse_ini_file()Parses a configuration file
    parse_ini_string()Parses a configuration string
    pathinfo()Returns information about a file path
    pclose()Closes a pipe opened by popen()
    popen()Opens a pipe
    readfile()Reads a file and writes it to the output buffer
    readlink()Returns the target of a symbolic link
    realpath()Returns the absolute pathname
    realpath_cache_get()Returns realpath cache entries
    realpath_cache_size()Returns realpath cache size
    rename()Renames a file or directory
    rewind()Rewinds a file pointer
    rmdir()Removes an empty directory
    set_file_buffer()Alias of stream_set_write_buffer(). Sets the buffer size for write operations on the given file
    stat()Returns information about a file
    symlink()Creates a symbolic link
    tempnam()Creates a unique temporary file
    tmpfile()Creates a unique temporary file
    touch()Sets access and modification time of a file
    umask()Changes file permissions for files
    unlink()Deletes a file
    PHP Filesystem Reference

    Example

    Return filename from the specified path: <?php $path = "/testweb/home.php"; //Show filenameecho basename($path) ."<br/>"; //Show filename, but cut off file extension for ".php" files echo basename($path,".php"); ?> The output of the code above will be: home.php home

    Definition and Usage

    The basename() function returns the filename from a path.

    Syntax

    basename(path, suffix)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies a file path
    suffixOptional. A file extension. If the filename has this file extension, the file extension will be cut off

    Technical Details

    Return Value: The filename of the specified path
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Change the usergroup to "admin" for the "test.txt" file: <?php chgrp("test.txt","admin") ?>

    Definition and Usage

    The chgrp() function changes the usergroup of the specified file.

    Syntax

    chgrp(file, group)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to change user group for
    groupRequired. Specifies the new group name or number

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Change permissions for the "test.txt" file: <?php // Read and write for owner, nothing for everybody else chmod("test.txt",0600); // Read and write for owner, read for everybody else chmod("test.txt",0644); // Everything for owner, read and execute for everybody else chmod("test.txt",0755); // Everything for owner, read for owner's group chmod("test.txt",0740); ?>

    Definition and Usage

    The chmod() function changes permissions of the specified file.

    Syntax

    chmod(file, mode)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file
    modeRequired. Specifies the new permissions.The mode parameter consists of four numbers:
  • The first number is always zero
  • The second number specifies permissions for the owner
  • The third number specifies permissions for the owner's user group
  • The fourth number specifies permissions for everybody else
  • Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions
  • Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Change owner for the "test.txt" file: <?php chown("test.txt","charles") ?>

    Definition and Usage

    The chown() function changes the owner of the specified file.

    Syntax

    chown(file, owner)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to change owner for
    ownerRequired. Specifies the new owner. Can be a user name or a user ID.

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Output file size, truncate file, clear cache, and then output file size again: <?php //output filesize echo filesize("test.txt"); echo "<br />"; $file = fopen("test.txt", "a+"); // truncate file ftruncate($file,100); fclose($file); //Clear cache and check filesize again clearstatcache(); echo filesize("test.txt"); ?> The output of the code above could be: 792 100

    Definition and Usage

    The clearstatcache() function clears the file status cache. PHP caches data for some functions for better performance. If a file is to be checked several times in a script, you probably want to avoid caching to get correct results. To do this, use the clearstatcache() function.

    Syntax

    clearstatcache(clear_realpath_cache, filename)

    Parameter Values

    ParameterDescription
    clear_realpath_cacheOptional. Indicates whether to clear the realpath cache or not. Default is FALSE, which indicates not to clear realpath cache
    filenameOptional. Specifies a filename, and clears the realpath and cache for that file only

    Tips and Notes

    Tip: Functions that are caching:
  • stat()
  • lstat()
  • file_exists()
  • is_writable()
  • is_readable()
  • is_executable()
  • is_file()
  • is_dir()
  • is_link()
  • filectime()
  • fileatime()
  • filemtime()
  • fileinode()
  • filegroup()
  • fileowner()
  • filesize()
  • filetype()
  • fileperms()
  • Technical Details

    Return Value: Nothing
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3 - Added two optional parameters: clear_realpath_cahe and filename
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Copy "source.txt" to "target.txt": <?php echo copy("source.txt","target.txt"); ?>

    Definition and Usage

    The copy() function copies a file. Note: If the to_file file already exists, it will be overwritten.

    Syntax

    copy(from_file, to_file, context)

    Parameter Values

    ParameterDescription
    from_fileRequired. Specifies the path to the file to copy from
    to_fileRequired. Specifies the path to the file to copy to
    contextOptional. Specifies a context resource created with stream_context_create()

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3 - Added context parameter
    PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    There is no delete() function in PHP. If you need to delete a file, look at the unlink() function. PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the path of the parent directory: <?php echo dirname("c:/testweb/home.php") . "<br />";echo dirname("c:/testweb/home.php", 2) . "<br />"; echo dirname("/testweb/home.php"); ?> The output of the code above will be: c:/testwebc: /testweb

    Definition and Usage

    The dirname() function returns the path of the parent directory.

    Syntax

    dirname(path, levels)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies a path to check
    levelsOptional. An integer that specifies the number of parent directories to go up. Default is 1

    Technical Details

    Return Value: The path of the parent directory on success
    PHP Version: 4.0+
    Binary Safe: Yes, in PHP 5.0
    PHP Changelog: PHP 7.0 - Added the levels parameter
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the free space, in bytes, of the C: directory: <?php echo disk_free_space("C:"); ?> The output of the code above could be: 109693288448

    Definition and Usage

    The disk_free_space() function returns the free space, in bytes, of the specified filesystem or disk. Tip: Look at the disk_total_space() to get the total size of a filesystem or disk.

    Syntax

    disk_free_space(directory)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the filesystem or disk to check

    Technical Details

    Return Value: The number of free space (in bytes) on success, FALSE on failure
    PHP Version: 4.1+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the total size, in bytes, of the C: directory: <?php echo disk_total_space("C:"); ?> The output of the code above could be: 119990349824

    Definition and Usage

    The disk_total_space() function returns the total size, in bytes, of the specified filesystem or disk. Tip: Look at the disk_free_space() to get the free space of a filesystem or disk.

    Syntax

    disk_total_space(directory)

    Parameter Values

    ParameterDescription
    directoryRequired. Specifies the filesystem or disk to check

    Technical Details

    Return Value: The number of total size (in bytes) on success, FALSE on failure
    PHP Version: 4.1+
    PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    The diskfreespace() function is an alias of the disk_free_space() function. PHP Filesystem Reference PHP Filesystem Reference

    Example

    Open and close file "test.txt": <?php $file = fopen("test.txt", "r"); fclose($file); ?> Run Example »

    Definition and Usage

    The fclose() function closes an open file. Note: The file must have been opened by fopen() or fsockopen().

    Syntax

    fclose(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the file to close

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Open file, read lines - until EOF is reached: <?php $file = fopen("test.txt", "r"); //Output lines until EOF is reached while(! feof($file)) { $line = fgets($file); echo $line. "<br>";} fclose($file); ?> Run Example »

    Definition and Usage

    The feof() function checks if the "end-of-file" (EOF) has been reached for an open file. Tip: This function is useful for looping through data of unknown length.

    Syntax

    feof(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies an open file to check

    Technical Details

    Return Value: TRUE if EOF is reached or an error occurs, FALSE otherwise
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Write all buffered output to the open file: <?php $file = fopen("test.txt","r+"); rewind($file);fwrite($file, 'Hello World');fflush($file); fclose($file);?>

    Definition and Usage

    The fflush() function writes all buffered output to an open file.

    Syntax

    fflush(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to write the buffered output to

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0.1+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read one character from the open file: <?php $file = fopen("test.txt","r"); echo fgetc($file); fclose($file); ?> Run Example »

    Definition and Usage

    The fgetc() function returns a single character from an open file. Note: This function is slow and should not be used on large files. If you need to read one character at a time from a large file, use fgets() to read data one line at a time and then process the line one single character at a time with fgetc().

    Syntax

    fgetc(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to return a single character from

    Technical Details

    Return Value: A single character read from the file on success, FALSE on EOF
    PHP Version: 4.0+
    Binary Safe: Yes

    More Examples

    Example

    Read open file, character by character: <?php $file = fopen("test.txt","r"); while (! feof($file)) { echo fgetc($file); } fclose($file); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read and output one line from the open CSV file: <?php $file = fopen("contacts.csv","r"); print_r(fgetcsv($file)); fclose($file); ?> Run Example »

    Definition and Usage

    The fgetcsv() function parses a line from an open file, checking for CSV fields. Tip: Also see the fputcsv() function.

    Syntax

    fgetcsv(file, length, separator, enclosure)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to return and parse a line from
    lengthOptional. Specifies the maximum length of a line. Must be greater than the longest line (in characters) in the CSV file. Omitting this parameter (or setting it to 0) the line length is not limited, which is slightly slower. Note: This parameter is required in versions prior to PHP 5
    separatorOptional. Specifies the field separator. Default is comma ( , )
    enclosureOptional. Specifies the field enclosure character. Default is "
    escapeOptional. Specifies the escape character. Default is "\\"

    Technical Details

    Return Value: An array with the CSV fields on success, NULL if an invalid file is supplied, FALSE on other errors and on EOF
    PHP Version: 4.0+
    Binary Safe: Yes, in PHP 4.3.5
    PHP Changelog: PHP 5.3 - Added the escape parameter

    More Examples

    Example

    Read and output the entire contents of a CSV file: <?php $file = fopen("contacts.csv","r"); while(! feof($file)) { print_r(fgetcsv($file)); } fclose($file); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read one line from the open file: <?php $file = fopen("test.txt","r"); echo fgets($file); fclose($file); ?> Run Example »

    Definition and Usage

    The fgets() function returns a line from an open file.

    Syntax

    fgets(file, length)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to return a line from
    lengthOptional. Specifies the number of bytes to read. Reading stops when length-1 bytes have been reached, or when a new line occurs, or on EOF. If no length is specified, it reads until end of the line

    Technical Details

    Return Value: A single line read from the file on success, FALSE on EOF or error
    PHP Version: 4.0+
    Binary Safe: Yes, in PHP 4.3

    More Examples

    Example

    Read open file, line by line: <?php $file = fopen("test.txt","r"); while(! feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read one line from the open HTML file (strip tags): <?php $file = fopen("test.htm","r"); echo fgetss($file); fclose($file); ?> Run Example »

    Definition and Usage

    The fgetss() function returns a line from an open file - stripped from HTML and PHP tags. Note: The fgetss() function is deprecated from PHP 7.3.

    Syntax

    fgetss(file, length, tags)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to return a line from
    lengthOptional. Specifies the number of bytes to read. Reading stops when length-1 bytes have been reached, or a when a new line occurs, or on EOF. Note: This parameter is required in versions prior to PHP 5
    tagsOptional. Specifies which tags that will not be removed

    Technical Details

    Return Value: A single line read from the file on success, FALSE on EOF or error
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read a file into an array: <?php print_r(file("test.txt")); ?> Run Example »

    Definition and Usage

    The file() reads a file into an array. Each array element contains a line from the file, with the newline character still attached.

    Syntax

    file(filename, flag, context)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to read
    flag Optional. Can be one or more of the following constants:
  • FILE_USE_INCLUDE_PATH - Search for the file in the include_path (in php.ini)
  • FILE_IGNORE_NEW_LINES - Skip the newline at the end of each array element
  • FILE_SKIP_EMPTY_LINES - Skip empty lines in the file
  • contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.

    Technical Details

    Return Value: The entire file in an array, FALSE on failure
    PHP Version: 4.0+
    Binary Safe: Yes, in PHP 4.3
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether a file exists: <?php echo file_exists("test.txt"); ?> Run Example »

    Definition and Usage

    The file_exists() function checks whether a file or directory exists. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    file_exists(path)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the path to the file or directory to check

    Technical Details

    Return Value: TRUE if the file or directory exists, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read a file into a string: <?php echo file_get_contents("test.txt"); ?> Run Example »

    Definition and Usage

    The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

    Syntax

    file_get_contents(path, include_path, context, start, max_length)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the path to the file to read
    include_pathOptional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.
    startOptional. Specifies where in the file to start reading. Negative values count from the end of the file
    max_lengthOptional. Specifies the maximum length of data read. Default is read to EOF

    Technical Details

    Return Value: The entire file in a string, FALSE on failure
    PHP Version: 4.3+
    Binary Safe: Yes, in PHP 4.3
    PHP Changelog: PHP 7.1 - Support for negative values in start parameterPHP 5.1 - Added the start and max_length parameters
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Write data to a file: <?php echo file_put_contents("test.txt","Hello World. Testing!"); ?> The output of the code above will be: 21

    Definition and Usage

    The file_put_contents() writes data to a file. This function follows these rules when accessing a file:
    1. If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename
    2. Create the file if it does not exist
    3. Open the file
    4. Lock the file if LOCK_EX is set
    5. If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
    6. Write the data into the file
    7. Close the file and release any locks
    Note: Use FILE_APPEND to avoid deleting the existing content of the file.

    Syntax

    file_put_contents(filename, data, mode, context)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to write to. If the file does not exist, this function will create one
    dataRequired. The data to write to the file. Can be a string, array, or a data stream
    modeOptional. Specifies how to open/write to the file. Possible values:
  • FILE_USE_INCLUDE_PATH - search for filename in the include directory
  • FILE_APPEND - if file already exists, append the data to it - instead of overwriting it
  • LOCK_EX - Put an exclusive lock on the file while writing to it
  • contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream.

    Technical Details

    Return Value: The number of bytes written into the file on success, FALSE on failure
    PHP Version: 5.0+
    Binary Safe: Yes
    PHP Changelog: PHP 5.1 - Added support for LOCK_EX and the ability to pass a stream resource to the data parameter
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get last access time of "webdictionary.txt": <?php echo fileatime("webdictionary.txt"); echo "<br>"; echo "Last access: ".date("F d Y H:i:s.", fileatime("webdictionary.txt")); ?> Run Example »

    Definition and Usage

    The fileatime() function returns the last access time of the specified file. Note: The result of this function is cached. Use clearstatcache() to clear the cache. Note: The atime of a file changes each time the data of a file are being read. This can decrease the performance if an application accesses a large number of files or directories. Some Unix systems have access time updates disabled to increase performance. In this case this function is useless.

    Syntax

    fileatime(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The last access time as a Unix timestamp on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get last change time of "webdictionary.txt": <?php echo filectime("webdictionary.txt"); echo "<br>"; echo "Last changed: ".date("F d Y H:i:s.", filectime("webdictionary.txt")); ?> Run Example »

    Definition and Usage

    The filectime() function returns the last time a file was changed. This function checks for inode changes as well as regular changes. Inode changes is when permissions, owner, group or other metadata is changed. Tip: Use the filemtime() function to return the last time the file content was changed. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    filectime(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The last change time as a Unix timestamp on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the group ID of "test.txt": <?php echo filegroup("test.txt"); ?> Run Example »

    Definition and Usage

    The filegroup() function returns the group ID of a file. Tip: Use the posix_getgrgid() function to convert the group ID to a group name. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    filegroup(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The group ID for the file on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the file inode of "test.txt": <?php echo fileinode("test.txt"); ?> Run Example »

    Definition and Usage

    The fileinode() function returns the inode of the specified file. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    fileinode(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The inode number of the file on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get the last time the file content was modified: <?php echo filemtime("webdictionary.txt"); echo "<br>"; echo "Content last changed: ".date("F d Y H:i:s.", filemtime("webdictionary.txt")); ?> Run Example »

    Definition and Usage

    The filemtime() function returns the last time the file content was modified. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    filemtime(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The last time the file content was modified as a Unix timestamp, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the user ID (owner) of "test.txt": <?php echo fileowner("test.txt"); ?> Run Example »

    Definition and Usage

    The fileowner() function returns the user ID (owner) of the specified file. Tip: Use posix_getpwuid() to convert the user ID to a user name. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    fileowner(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The user ID of the owner of the file on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the file permissions for "test.txt": <?php echo fileperms("test.txt"); ?> Run Example »

    Definition and Usage

    The fileperms() function returns the permissions for a file. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    fileperms(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The file's permissions as a number, FALSE on failure
    PHP Version: 4.0+

    More Examples

    Example

    Display permissions as an octal value: <?php echo substr(sprintf("%o",fileperms("test.txt")),-4); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the file size for "test.txt": <?php echo filesize("test.txt"); ?> Run Example »

    Definition and Usage

    The filesize() function returns the size of a file. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    filesize(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to check

    Technical Details

    Return Value: The file size in bytes on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the file type for "test.txt": <?php echo filetype("test.txt"); ?> Run Example »

    Definition and Usage

    The filetype() function returns the file type of a file. Possible return values:
  • fifo
  • char
  • dir
  • block
  • link
  • file
  • socket
  • unknown
  • Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    filetype(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file to check

    Technical Details

    Return Value: One of the file types on success, FALSE on failure
    PHP Version: 4.0+

    More Examples

    Example

    Return the file type for /images/: <?php echo filetype("/images/"); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Example

    Lock and release a file: <?php $file = fopen("test.txt","w+"); // exclusive lock if (flock($file,LOCK_EX)) { fwrite($file,"Add some text to the file."); fflush($file); // release lock flock($file,LOCK_UN); } else { echo "Error locking file!"; } fclose($file); ?>

    Definition and Usage

    The flock() function locks and releases a file.

    Syntax

    flock(file, lock, block)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies an open file to lock or release
    lockRequired. Specifies what kind of lock to use.Possible values:
  • LOCK_SH - A shared lock (reader). Allow other processes to access the file
  • LOCK_EX - An exclusive lock (writer). Prevent other processes from accessing the file
  • LOCK_UN - Release the lock
  • LOCK_NB - Avoid blocking other processes while locking
  • blockOptional. Set to 1 to block other processes while locking

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.5: Added support for the block parameter on WindowsPHP 5.3: Removed automatic unlocking on fclose(). Unlocking must now be done manually
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Checking a color name against a shell wildcard pattern: <?php $txt = "My car is a dark color"; if (fnmatch("*col[ou]r",$txt)) { echo "hmm..."; } ?>

    Definition and Usage

    The fnmatch() function checks if a string or filename matches the given shell wildcard pattern.

    Syntax

    fnmatch(pattern, string, flags)

    Parameter Values

    ParameterDescription
    patternRequired. Specifies the shell wildcard pattern
    stringRequired. Specifies the string or file to check
    flagsOptional. Can be one or a combination of the following:
  • FNM_NOESCAPE - Disable backslash escaping
  • FNM_PATHNAME - Slash in string only matches slash in the given pattern
  • FNM_PERIOD - Leading period in string must be exactly matched by period in pattern
  • FNM_CASEFOLD - Caseless match. Part of the GNU extension
  • Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.3+
    PHP Changelog: PHP 5.3: Now available on Windows platforms
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Open file, read lines - until EOF is reached: <?php $file = fopen("test.txt", "r"); //Output lines until EOF is reached while(! feof($file)) { $line = fgets($file); echo $line. "<br>";} fclose($file); ?> Run Example »

    Definition and Usage

    The fopen() function opens a file or URL. Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character. Windows offers a translation flag ('t') which will translate \n to \r\n when working with the file. You can also use 'b' to force binary mode. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

    Syntax

    fopen(filename, mode, include_path, context)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file or URL to open
    modeRequired. Specifies the type of access you require to the file/stream.Possible values:
  • "r" - Read only. Starts at the beginning of the file
  • "r+" - Read/Write. Starts at the beginning of the file
  • "w" - Write only. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "w+" - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist
  • "a+" - Read/Write. Preserves file content by writing to the end of the file
  • "x" - Write only. Creates a new file. Returns FALSE and an error if file already exists
  • "x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • "c" - Write only. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "e" - Only available in PHP compiled on POSIX.1-2008 conform systems.
  • include_pathOptional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: TRUE on success, FALSE and an error on failure. You can hide the error by adding an "@" in front of the function name.
    PHP Version: 4.3+
    PHP Changelog: PHP 7.1: Added "e" optionPHP 5.2: Added "c" and "c+" options
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read from the current position in file - until EOF, and then write the remaining data to the output buffer: <?php $file = fopen("test.txt","r"); // Read first line fgets($file); // Read from the current position in file - until EOF, and then write the result to the output buffer echo fpassthru($file); fclose($file); ?> Run Example »

    Definition and Usage

    The fpassthru() function reads from the current position in a file - until EOF, and then writes the result to the output buffer. Note: When using fpassthru() on a binary file on Windows, remember to open the file in binary mode. Tip: Call rewind() to set the file pointer to the beginning of the file if you have already written to the file. Tip: To just dump the contents of a file to the output buffer, use the readfile() function instead.

    Syntax

    fpassthru(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to read from

    Technical Details

    Return Value: The number of characters read from the file and passed through the output or FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Format a line as CSV and writes it to an open file: <?php $list = array ( array("Peter", "Griffin" ,"Oslo", "Norway"), array("Glenn", "Quagmire", "Oslo", "Norway") ); $file = fopen("contacts.csv","w"); foreach ($list as $line) { fputcsv($file, $line); } fclose($file);?>

    Definition and Usage

    The fputcsv() function formats a line as CSV and writes it to an open file. Tip: Also see the fgetcsv() function.

    Syntax

    fputcsv(file, fields, separator, enclosure, escape)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to write to
    fields Required. Specifies which array to get the data from
    separatorOptional. A character that specifies the field separator. Default is comma ( , )
    enclosureOptional. A character that specifies the field enclosure character. Default is "
    escapeOptional. Specifies the escape character. Default is "\\". Can also be an empty string (") which disables the escape mechanism

    Technical Details

    Return Value: The length of the written string on success, FALSE on failure
    PHP Version: 5.1+
    PHP Changelog: PHP 7.4 - The escape parameter now accepts an empty string to disable the escape mechanism PHP 5.5 - Added the escape parameter
    PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    The fputs() function is an alias of the fwrite() function. PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read 10 bytes from an open file: <?php $file = fopen("test.txt","r"); fread($file,"10"); fclose($file); ?> Run Example »

    Definition and Usage

    The fread() reads from an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first.

    Syntax

    fread(file, length)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to read from
    lengthRequired. Specifies the maximum number of bytes to read

    Technical Details

    Return Value: The read string, FALSE on failure
    PHP Version: 4.0+
    Binary Safe: Yes

    More Examples

    Example

    Read entire file: <?php $file = fopen("test.txt","r"); fread($file,filesize("test.txt")); fclose($file); ?> Run Example » PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    The fscanf() function parses the input from an open file according to the specified format. Note: Any whitespace in the format string matches any whitespace in the input stream. This means that a tab (\t) in the format string can match a single space character in the input stream.

    Syntax

    fscanf(file, format, mixed)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the file to check
    formatRequired. Specifies the format.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number
  • %e - Scientific notation (e.g. 1.2e+2)
  • %u - Unsigned decimal number
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    mixedOptional.

    Technical Details

    Return Value: The read string, FALSE on failure
    PHP Version: 4.0.1+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read first line from the open file, then move the file pointer back to the beginning of the file: <?php $file = fopen("test.txt","r");// Read first line echo fgets($file);// Move back to beginning of filefseek($file,0); fclose($file); ?> Run Example »

    Definition and Usage

    The fseek() function seeks in an open file. This function moves the file pointer from its current position to a new position, forward or backward, specified by the number of bytes. Tip: You can find the current position by using ftell()!

    Syntax

    fseek(file, offset, whence)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to seek in
    offsetRequired. Specifies the new position (measured in bytes from the beginning of the file)
    whenceOptional. Possible values:
  • SEEK_SET - Set position equal to offset. Default
  • SEEK_CUR - Set position to current location plus offset
  • SEEK_END - Set position to EOF plus offset (to move to a position before EOF, the offset must be a negative value)
  • Technical Details

    Return Value: 0 on success, otherwise -1
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return information about the open file: <?php $file = fopen("test.txt","r");print_r(fstat($file)); fclose($file); ?> Run Example »

    Definition and Usage

    The fstat() function returns information about an open file. Note: The results from this function will differ from server to server. The array may contain the number index, the name index, or both. Tip: This function is similar to stat(), except that with this function the file must be open.

    Syntax

    fstat(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to check

    Technical Details

    Return Value: An array with information about the open file:
  • [0] or [dev] - Device number
  • [1] or [ino] - Inode number
  • [2] or [mode] - Inode protection mode
  • [3] or [nlink] - Number of links
  • [4] or [uid] - User ID of owner
  • [5] or [gid] - Group ID of owner
  • [6] or [rdev] - Inode device type
  • [7] or [size] - Size in bytes
  • [8] or [atime] - Last access (as Unix timestamp)
  • [9] or [mtime] - Last modified (as Unix timestamp)
  • [10] or [ctime] - Last inode change (as Unix timestamp)
  • [11] or [blksize] - Blocksize of filesystem IO (if supported)
  • [12] or [blocks] - Number of blocks allocated
  • PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the current position of the read/write pointer in an open file: <?php $file = fopen("test.txt","r");// Print current position echo ftell($file); // Change current position fseek($file,"15"); // Print current position again echo "<br>" . ftell($file); fclose($file); ?> Run Example »

    Definition and Usage

    The ftell() function returns the current position of the read/write pointer in an open file.

    Syntax

    ftell(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to check

    Technical Details

    Return Value: The file pointer position, or FALSE on failure.
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Truncates an open file to the specified length (100 bytes): <?php // Check filesize echo filesize("test.txt"); echo "<br>"; $file = fopen("test.txt", "a+"); ftruncate($file,100); fclose($file); // Clear cache and check filesize again clearstatcache(); echo filesize("test.txt"); ?> The output of the code above will be: 792 100

    Definition and Usage

    The ftruncate() function truncates an open file to the specified length.

    Syntax

    ftruncate(file, size)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to truncate
    sizeRequired. Specifies the new file size

    Technical Details

    Return Value: TRUE on success, or FALSE on failure.
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Write to an open file: <?php $file = fopen("test.txt","w"); echo fwrite($file,"Hello World. Testing!"); fclose($file); ?> The output of the code above will be: 21

    Definition and Usage

    The fwrite() writes to an open file. The function will stop at the end of the file (EOF) or when it reaches the specified length, whichever comes first.

    Syntax

    fwrite(file, string, length)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file to write to
    stringRequired. Specifies the string to write to the open file
    lengthOptional. Specifies the maximum number of bytes to write

    Technical Details

    Return Value: The number of bytes written, FALSE on failure
    PHP Version: 4.0+
    Binary Safe: Yes
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return an array of filenames or directories that matches the specified pattern: <?php print_r(glob("*.txt")); ?> The output of the code above could be: Array ( [0] => target.txt [1] => source.txt [2] => test.txt [3] => test2.txt )

    Definition and Usage

    The glob() function returns an array of filenames or directories matching a specified pattern.

    Syntax

    glob(pattern, flags)

    Parameter Values

    ParameterDescription
    patternRequired. Specifies the pattern to search for
    flagsOptional. Specifies special settings.Possible values:
  • GLOB_MARK - Adds a slash to each item returned
  • GLOB_NOSORT - Return files as they appear in the directory (unsorted)
  • GLOB_NOCHECK - Returns the search pattern if no match were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directories which match the pattern
  • GLOB_ERR - (added in PHP 5.1) Stop on errors (errors are ignored by default)
  • Technical Details

    Return Value: An array of files/directories that matches the pattern, FALSE on failure
    PHP Version: 4.3+
    PHP Changelog: PHP 5.1: GLOB_ERR value added to the flags parameter

    More Examples

    Example

    Return an array of filenames or directories that matches the specified pattern: <?php print_r(glob("*.*")); ?> The output of the code above could be: Array ( [0] => contacts.csv [1] => default.php [2] => target.txt [3] => source.txt [4] => tem1.tmp [5] => test.htm [6] => test.ini [7] => test.php [8] => test.txt [9] => test2.txt ) PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is a directory: <?php $file = "images"; if(is_dir($file)) { echo ("$file is a directory"); } else { echo ("$file is not a directory"); } ?> The output of the code above could be: images is a directory

    Definition and Usage

    The is_dir() function checks whether the specified filename is a directory. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_dir(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the directory exists, FALSE otherwise
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is executable: <?php $file = "setup.exe"; if(is_executable($file)) { echo ("$file is executable"); } else { echo ("$file is not executable"); } ?> The output of the code above could be: setup.exe is executable

    Definition and Usage

    The is_executable() function checks whether the specified filename is executable. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_executable(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is executable, FALSE and an E_WARNING on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is a regular file: <?php $file = "test.txt"; if(is_file($file)) { echo ("$file is a regular file"); } else { echo ("$file is not a regular file"); } ?> The output of the code above could be: test.txt is a regular file

    Definition and Usage

    The is_file() function checks whether the specified filename is a regular file. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_file(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is a regular file, FALSE otherwise
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is a symbolic link: <?php $link = "images"; if(is_link($link)) { echo ("$link is a link"); } else { echo ("$link is not a link"); } ?> The output of the code above could be: images is not a link

    Definition and Usage

    The is_link() function checks whether the specified filename is a symbolic link. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_link(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is a symbolic link, FALSE and an E_WARNING otherwise
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is readable: <?php $file = "test.txt"; if(is_readable($file)) { echo ("$file is readable"); } else { echo ("$file is not readable")} ?> The output of the code above could be: test.txt is readable

    Definition and Usage

    The is_readable() function checks whether the specified filename is readable. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_readable(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is readable, FALSE and an E_WARNING otherwise
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is uploaded via HTTP POST: <?php $file = "test.txt"; if(is_uploaded_file($file)) { echo ("$file is uploaded via HTTP POST"); } else { echo ("$file is not uploaded via HTTP POST"); } ?> The output of the code above could be: test.txt is not uploaded via HTTP POST

    Definition and Usage

    The is_uploaded_file() function checks whether the specified file is uploaded via HTTP POST.

    Syntax

    is_uploaded_file(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is uploaded via HTTP POST, FALSE on failure
    PHP Version: 4.0.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Check whether the specified filename is writable: <?php $file = "test.txt"; if(is_writable($file)) { echo ("$file is writable"); } else { echo ("$file is not writable"); } ?> The output of the code above could be: test.txt is writable

    Definition and Usage

    The is_writable() function checks whether the specified filename is writable. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    is_writable(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the file to check

    Technical Details

    Return Value: TRUE if the file is writable, an E_WARNING on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    The is_writeable() function is an alias of the is_writable() function. PHP Filesystem Reference PHP Filesystem Reference

    Example

    Change the group ownership of a symbolic link: <?php $target = "downloads.php";$link = "downloads";symlink($target, $link); lchgrp($link, 8)?>

    Definition and Usage

    The lchgrp() function changes the group ownership of a symbolic link. Note: This is not an HTML link, but a link in the filesystem. Note: This function does not work on Windows platforms.

    Syntax

    lchgrp(file, group)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the symlink
    groupRequired. Specifies the new group by name or number

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 5.1.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Change the user ownership of a symbolic link: <?php $target = "downloads.php";$link = "downloads";symlink($target, $link); lchown($link, 8)?>

    Definition and Usage

    The lchown() function changes the user ownership of a symbolic link. Note: This is not an HTML link, but a link in the filesystem. Note: This function does not work on Windows platforms.

    Syntax

    lchown(file, group)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the symlink
    groupRequired. Specifies the new user by name or number

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 5.1.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create a hard link: <?php $target = "text.txt";$linkname = "mylink";link($target, $linkname); ?>

    Definition and Usage

    The link() function creates a hard link.

    Syntax

    link(target, link)

    Parameter Values

    ParameterDescription
    targetRequired. Specifies the target
    linkRequired. Specifies the name of the link

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3.0: Now available on Windows platforms
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Verify if a link really exists: <?php echo linkinfo(/rubbish); ?>

    Definition and Usage

    The linkinfo() function returns information about a hard link, and is used to verify if a link really exists.

    Syntax

    linkinfo(path)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the path to check

    Technical Details

    Return Value: The device ID returned by lstat system call on success, FALSE or 0 on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3.0: Now available on Windows platforms
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get information about a file: <?php print_r(lstat("test.txt")); ?> Run Example »

    Definition and Usage

    The lstat() function returns information about a file or symbolic link. Note: The results from this function will differ from server to server. The array may contain the number index, the name index, or both. Note: The result of this function is cached. Use clearstatcache() to clear the cache. Tip: This function is similar to stat(), except that if the filename parameter is a symbolic link, the status of the symbolic link is returned.

    Syntax

    lstat(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file or a symbolic link to check

    Technical Details

    Return Value: An array with the following elements:
  • [0] or [dev] - Device number
  • [1] or [ino] - Inode number
  • [2] or [mode] - Inode protection mode
  • [3] or [nlink] - Number of links
  • [4] or [uid] - User ID of owner
  • [5] or [gid] - Group ID of owner
  • [6] or [rdev] - Inode device type
  • [7] or [size] - Size in bytes
  • [8] or [atime] - Last access (as Unix timestamp)
  • [9] or [mtime] - Last modified (as Unix timestamp)
  • [10] or [ctime] - Last inode change (as Unix timestamp)
  • [11] or [blksize] - Blocksize of filesystem IO (if supported)
  • [12] or [blocks] - Number of blocks allocated
  • It returns an E_WARNING on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create a directory named "test": <?php mkdir("test"); ?>

    Definition and Usage

    The mkdir() function creates a directory specified by a pathname.

    Syntax

    mkdir(path, mode, recursive, context)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the directory path to create
    modeOptional. Specifies permissions. By default, the mode is 0777 (widest possible access).Note: The mode parameters is ignored on Windows platforms! The mode parameter consists of four numbers:
  • The first number is always zero
  • The second number specifies permissions for the owner
  • The third number specifies permissions for the owner's user group
  • The fourth number specifies permissions for everybody else
  • Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions
  • recursiveOptional. Specifies if the recursive mode is set (added in PHP 5)
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream (added in PHP 5)

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Definition and Usage

    The move_uploaded_file() function moves an uploaded file to a new destination. Note: This function only works on files uploaded via PHP's HTTP POST upload mechanism. Note: If the destination file already exists, it will be overwritten.

    Syntax

    move_uploaded_file(file, dest)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the filename of the uploaded file
    destRequired. Specifies the new location for the file

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Contents of "test.ini": [names] me = Robert you = Peter [urls] first = "http://www.example.com" second = "https://www.w3schools.com" PHP code: <?php print_r(parse_ini_file("test.ini")); ?> The output of the code above will be: Array ( [me] => Robert [you] => Peter [first] => http://www.example.com [second] => https://www.w3schools.com )

    Definition and Usage

    The parse_ini_file() function parses a configuration (ini) file and returns the settings. Tip: This function can be used to read in your own configuration files, and has nothing to do with the php.ini file. Note: The following reserved words must not be used as keys for ini files: null, yes, no, true, false, on, off, none. Furthermore, the following reserved characters must not be used in the key: {}|&~!()^".

    Syntax

    parse_ini_file(file, process_sections, scanner_mode)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the ini file to parse
    process_sectionsOptional. If set to TRUE, it returns is a multidimensional array with section names and settings included. Default is FALSE
    scanner_mode Optional. Can be one of the following values:
  • INI_SCANNER_NORMAL (default)
  • INI_SCANNER_RAW (means option values will not be parsed)
  • INI_SCANNER_TYPED (means that boolean, null and integer types are preserved when possible. "true", "on", "yes" are converted to TRUE. "false", "off", "no", "none" are converted to FALSE. "null" is converted to NULL. Numeric strings are converted to integer type if possible)
  • Technical Details

    Return Value: An array on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 7.0: Hash marks (#) is no longer recognized as commentsPHP 5.6.1: Added INI_SCANNER_TYPED modePHP 5.3: Added optional scanner_mode parameter

    More Examples

    Example

    Contents of "test.ini": [names] me = Robert you = Peter [urls] first = "http://www.example.com" second = "https://www.w3schools.com" PHP code (with process_sections set to true): <?php print_r(parse_ini_file("test.ini",true)); ?> The output of the code above will be: Array ( [names] => Array ( [me] => Robert [you] => Peter ) [urls] => Array ( [first] => http://www.example.com [second] => https://www.w3schools.com ) ) PHP Filesystem Reference PHP Filesystem Reference

    Example

    Parse an ini string: $ini = '[names] me = "Robert" you = "Peter" [urls] first = "http://www.example.com" second = "https://www.w3schools.com" ';print_r(parse_ini_string($ini)); The output of the code above will be: Array ( [names] => Array ( [me] => Robert [you] => Peter ) [urls] => Array ( [first] => http://www.example.com [second] => https://www.w3schools.com ) )

    Definition and Usage

    The parse_ini_file() function parses a configuration (ini) string and returns the settings. Tip: This function can be used to read in your own configuration files, and has nothing to do with the php.ini file. Note: The following reserved words must not be used as keys for ini files: null, yes, no, true, false, on, off, none. Furthermore, the following reserved characters must not be used in the key: {}|&~!()^".

    Syntax

    parse_ini_string(ini, process_sections, scanner_mode)

    Parameter Values

    ParameterDescription
    iniRequired. Specifies the ini file to parse
    process_sectionsOptional. If set to TRUE, it returns is a multidimensional array with section names and settings included. Default is FALSE
    scanner_mode Optional. Can be one of the following values:
  • INI_SCANNER_NORMAL (default)
  • INI_SCANNER_RAW (means option values will not be parsed)
  • INI_SCANNER_TYPED (means that boolean, null and integer types are preserved when possible. "true", "on", "yes" are converted to TRUE. "false", "off", "no", "none" are converted to FALSE. "null" is converted to NULL. Numeric strings are converted to integer type if possible)
  • Technical Details

    Return Value: An array on success, FALSE on failure
    PHP Version: 5.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get information about a file path: <?php print_r(pathinfo("/testweb/test.txt")); ?> The output of the code above will be: Array ( [dirname] => /testweb [basename] => test.txt [extension] => txt )

    Definition and Usage

    The pathinfo() function returns information about a file path.

    Syntax

    pathinfo(path, options)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the path to be checked
    optionsOptional. Specifies which array element to return. If not specified, it returns all elements.Possible values:
  • PATHINFO_DIRNAME - return only dirname
  • PATHINFO_BASENAME - return only basename
  • PATHINFO_EXTENSION - return only extension
  • PATHINFO_FILENAME - return only filename
  • Technical Details

    Return Value: If the option parameter is omitted, it returns an associative array with dirname, basename, extension, and filename. If the option parameter is specified, it returns a string with the requested element. FALSE on failure
    PHP Version: 4.0.3+
    PHP Changelog: PHP 5.2: PATHINFO_FILENAME was added

    More Examples

    Example

    Get information about a file path: <?php print_r(pathinfo("/testweb/test.txt",PATHINFO_BASENAME)); ?> The output of the code above will be: test.txt PHP Filesystem Reference PHP Filesystem Reference

    Example

    Open and close a pipe to the program specified in the command parameter: <?php $file = popen("/bin/ls","r"); //some code to be executed pclose($file); ?>

    Definition and Usage

    The pclose() function closes a pipe opened by popen().

    Syntax

    pclose(pipe)

    Parameter Values

    ParameterDescription
    pipeRequired. Specifies the pipe opened by popen()

    Technical Details

    Return Value: The termination status, -1 on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Open a pipe to the program specified in the command parameter: <?php $file = popen("/bin/ls","r"); //some code to be executed pclose($file); ?>

    Definition and Usage

    The popen() function opens a pipe to the program specified in the command parameter.

    Syntax

    popen(command, mode)

    Parameter Values

    ParameterDescription
    commandRequired. Specifies the command to execute
    modeRequired. Specifies the connection mode. Can be "r" (Read only) or "w" (Write only - opens and clears existing file or creates a new file)

    Technical Details

    Return Value: FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Read a file: <?php echo readfile("test.txt"); ?> Run Example »

    Definition and Usage

    The readfile() function reads a file and writes it to the output buffer. Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled in the php.ini file.

    Syntax

    readfile(file, include_path, context)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the file to read
    include_pathOptional. Set this parameter to TRUE if you want to search for the file in the include_path (in php.ini) as well
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: The number of bytes read on success, FALSE and an error on failure. You can hide the error message by adding an '@' in front of the function name
    PHP Version: 4.0+
    PHP Changelog: PHP 5.0: Added context support
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get the target of a symbolic link: <?php echo readlink("/user/testlink"); ?>

    Definition and Usage

    The readlink() function returns the target of a symbolic link.

    Syntax

    readlink(linkpath)

    Parameter Values

    ParameterDescription
    linkpathRequired. Specifies the link path to check

    Technical Details

    Return Value: The target of the link on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3: readlink() now available on Windows platforms
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Returns the absolute pathname: <?php echo realpath("test.txt"); ?> The output of the code above will be: C:\Inetpub\testweb\test.txt

    Definition and Usage

    The realpath() function returns the absolute pathname. This function removes all symbolic links (like '/./', '/../' and extra '/') and returns the absolute pathname.

    Syntax

    realpath(path)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies the path to check

    Technical Details

    Return Value: The absolute pathname on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3:PHP 5.2.1:
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return realpath cache entries: <?php var_dump(realpath_cache_get()); ?> Run Example »

    Definition and Usage

    The realpath_cache_get() function returns realpath cache entries.

    Syntax

    realpath_cache_get()

    Technical Details

    Return Value: An array of realpath cache entries
    PHP Version: 5.3.2+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return realpath cache size: <?php var_dump(realpath_cache_size()); ?> Run Example »

    Definition and Usage

    The realpath_cache_size() function returns realpath cache size.

    Syntax

    realpath_cache_size()

    Technical Details

    Return Value: How much memory realpath cache is using
    PHP Version: 5.3.2+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Rename a directory + a file: <?php rename("images","pictures");rename("/test/file1.txt","/home/docs/my_file.txt"); ?>

    Definition and Usage

    The rename() function renames a file or directory.

    Syntax

    rename(old, new, context)

    Parameter Values

    ParameterDescription
    oldRequired. Specifies the file or directory to be renamed
    newRequired. Specifies the new name for the file or directory
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3.1: Allow renaming files across drives in Windows.PHP 5.0: Can be used with some URL wrappers.
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Rewind the position of the file pointer to the beginning of the file: <?php $file = fopen("test.txt","r"); //Change position of file pointer fseek($file,"15"); //Set file pointer to 0 rewind($file); fclose($file); ?>

    Definition and Usage

    The rewind() function "rewinds" the position of the file pointer to the beginning of the file.

    Syntax

    rewind(file)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the open file

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Remove "images" directory: <?php $path = "images"; if(!rmdir($path)) { echo ("Could not remove $path"); } ?>

    Definition and Usage

    The rmdir() function removes an empty directory.

    Syntax

    rmdir(dir, context)

    Parameter Values

    ParameterDescription
    dirRequired. Specifies the path to the directory to be removed
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create an unbuffered stream: <?php $file = fopen("test.txt","w"); if ($file) { set_file_buffer($file,0); fwrite($file,"Hello World. Testing!"); fclose($file); } ?>

    Definition and Usage

    The set_file_buffer() function specifies the number of bytes to buffer on the given file. Output using fwrite() is normally buffered at 8K. So, if two processes writes to the same file, each will write up to 8K before pausing, and allow the other to write. If buffer is 0, write operations are unbuffered (meaning that the first write process will be completed before allowing other processes to write). Tip: This function is an alias of stream_set_write_buffer().

    Syntax

    set_file_buffer(file, buffer)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies a file pointer
    bufferRequired. Specifies the number of bytes to buffer

    Technical Details

    Return Value: 0 on success, another value if request failed
    PHP Version: 4.3+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Get information about a file: <?php $stat = stat("test.txt"); echo "Access time: " .$stat["atime"]; echo "<br>Modification time: " .$stat["mtime"]; echo "<br>Device number: " .$stat["dev"]; ?> Run Example »

    Definition and Usage

    The stat() function returns information about a file. Note: The results from this function will differ from server to server. The array may contain the number index, the name index, or both. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

    Syntax

    stat(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file

    Technical Details

    Return Value: An array with the following elements:
  • [0] or [dev] - Device number
  • [1] or [ino] - Inode number
  • [2] or [mode] - Inode protection mode
  • [3] or [nlink] - Number of links
  • [4] or [uid] - User ID of owner
  • [5] or [gid] - Group ID of owner
  • [6] or [rdev] - Inode device type
  • [7] or [size] - Size in bytes
  • [8] or [atime] - Last access (as Unix timestamp)
  • [9] or [mtime] - Last modified (as Unix timestamp)
  • [10] or [ctime] - Last inode change (as Unix timestamp)
  • [11] or [blksize] - Blocksize of filesystem IO (if supported)
  • [12] or [blocks] - Number of blocks allocated
  • It returns an E_WARNING on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create a symbolic link: <?php $target = "downloads.php";$link = "downloads";symlink($target, $link); echo readlink($link); ?>

    Definition and Usage

    The symlink() function creates a symbolic link from the existing target with the specified name link. Note: This is not an HTML link, but a link in the filesystem.

    Syntax

    symlink(target, link)

    Parameter Values

    ParameterDescription
    targetRequired. Specifies the target of the link
    linkRequired. Specifies the link name

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3: Available on Windows platforms
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create a temporary file with a unique name in the specified directory: <?php echo tempnam("C:\inetpub\testweb","TMP0"); ?> The output of the code above could be: C:\inetpub\testweb\TMP1.tmp

    Definition and Usage

    The tempnam() function creates a temporary file with a unique name in the specified directory. Note: If the specified directory does not exist, tempnam() may generate a file in the system's temporary directory. Tip: See also the tmpfile() function.

    Syntax

    tempnam(dir, prefix)

    Parameter Values

    ParameterDescription
    dirRequired. Specifies the directory of where to create the temp file
    prefixRequired. Specifies the start of the filename

    Technical Details

    Return Value: The new temporary filename, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog:
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Create a temporary file with a unique name in read-write (w+) mode: <?php $temp = tmpfile(); fwrite($temp, "Testing, testing."); //Rewind to the start of file rewind($temp); //Read 1k from file echo fread($temp,1024); //This removes the file fclose($temp); ?> The output of the code above will be: Testing, testing.

    Definition and Usage

    The tmpfile() function creates a temporary file with a unique name in read-write (w+) mode. Note: The file is automatically removed when closed, with fclose() or when the script ends. Tip: See also the tempnam() function.

    Syntax

    tmpfile()

    Technical Details

    Return Value: A file handle (similar to the one returned by fopen() for the new file), FALSE on failure
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Sets the access and modification time of the specified file: <?php filename = "test.txt";if (touch($filename)) { echo $filename . " modification time has been changed to present time";} else { echo "Sorry, could not change modification time of " . $filename;} ?>

    Definition and Usage

    The touch() function sets the access and modification time of the specified file. Note: If the specified file does not exist, it will be created.

    Syntax

    touch(filename, time, atime)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file to touch
    timeOptional. Sets the touch time. The current system time is set by default
    atimeOptional. Sets the access time. Default is the current system time if no parameters are set, or the same as the time parameter if that parameter is set

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3 -
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Return the current umask: <?php $file = "test.txt"; echo (umask()); ?>

    Definition and Usage

    The umask() function changes the file permissions for files. This function sets PHP's umask to mask & 0777 and returns the old umask.

    Syntax

    umask(mask)

    Parameter Values

    ParameterDescription
    maskOptional. Specifies the new permissions. Default is 0777 The mask parameter consists of four numbers:
  • The first number is always zero
  • The second number specifies permissions for the owner
  • The third number specifies permissions for the owner's user group
  • The fourth number specifies permissions for everybody else
  • Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions
  • Technical Details

    Return Value: If you call umask() without any arguments, it returns the current umask, otherwise it returns the old umask
    PHP Version: 4.0+
    PHP Filesystem Reference PHP Filesystem Reference

    Example

    Delete a file: <?php $file = fopen("test.txt","w"); echo fwrite($file,"Hello World. Testing!"); fclose($file);unlink("test.txt"); ?>

    Definition and Usage

    The unlink() function deletes a file.

    Syntax

    unlink(filename, context)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the path to the file to delete
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.0 - Added the context parameter
    PHP Filesystem Reference

    Filter Introduction

    This PHP filters is used to validate and filter data coming from insecure sources, like user input.

    Installation

    From PHP 5.2.0, the filter functions are enabled by default. There is no installation needed to use these functions.

    Runtime Configurations

    The behavior of these functions is affected by settings in php.ini:
    NameDescriptionDefaultChangeable
    filter.defaultFilter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. Accepts the name of the filter you like to use by default. See the filter list for the list of the filter names"unsafe_raw"PHP_INI_PERDIR
    filter.default_flagsDefault flags to apply when the default filter is set. This is set to FILTER_FLAG_NO_ENCODE_QUOTES by default for backwards compatibility reasonsNULLPHP_INI_PERDIR

    Filter Functions

    FunctionDescription
    filter_has_var()Checks whether a variable of a specified input type exist
    filter_id()Returns the filter ID of a specified filter name
    filter_input()Gets an external variable (e.g. from form input) and optionally filters it
    filter_input_array()Gets external variables (e.g. from form input) and optionally filters them
    filter_list()Returns a list of all supported filter names
    filter_var()Filters a variable with a specified filter
    filter_var_array()Gets multiple variables and filter them

    Predefined Filter Constants

    Constant Description
    INPUT_POST POST variables
    INPUT_GET GET variables
    INPUT_COOKIE COOKIE variables
    INPUT_ENV ENV variables
    INPUT_SERVER SERVER variables
    FILTER_DEFAULT Do nothing, optionally strip/encode special characters. Equivalent to FILTER_UNSAFE_RAW
    FILTER_FLAG_NONE Allows no flags
    FILTER_FLAG_ALLOW_OCTAL Only for inputs that starts with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7
    FILTER_FLAG_ALLOW_HEX Only for inputs that starts with 0x/0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9
    FILTER_FLAG_STRIP_LOW Strip characters with ASCII value lower than 32
    FILTER_FLAG_STRIP_HIGH Strip characters with ASCII value greater than 127
    FILTER_FLAG_ENCODE_LOW Encode characters with ASCII value lower than 32
    FILTER_FLAG_ENCODE_HIGH Encode characters with ASCII value greater than 127
    FILTER_FLAG_ENCODE_AMP Encode &
    FILTER_FLAG_NO_ENCODE_QUOTES Do not encode ' and "
    FILTER_FLAG_EMPTY_STRING_NULL Not in use
    FILTER_FLAG_ALLOW_FRACTION Allows a period (.) as a fractional separator in numbers
    FILTER_FLAG_ALLOW_THOUSAND Allows a comma (,) as a thousands separator in numbers
    FILTER_FLAG_ALLOW_SCIENTIFIC Allows an e or E for scientific notation in numbers
    FILTER_FLAG_PATH_REQUIRED The URL must contain a path part
    FILTER_FLAG_QUERY_REQUIRED The URL must contain a query string
    FILTER_FLAG_IPV4 Allows the IP address to be in IPv4 format
    FILTER_FLAG_IPV6 Allows the IP address to be in IPv6 format
    FILTER_FLAG_NO_RES_RANGE Fails validation for the reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4, and for the reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10
    FILTER_FLAG_NO_PRIV_RANGE Fails validation for the private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16, and for the IPv6 addresses starting with FD or FC
    FILTER_FLAG_EMAIL_UNICODE Allows the local part of the email address to contain Unicode characters
    FILTER_REQUIRE_SCALAR The value must be a scalar
    FILTER_REQUIRE_ARRAY The value must be an array
    FILTER_FORCE_ARRAY Treats a scalar value as array with the scalar value as only element
    FILTER_NULL_ON_FAILURE Return NULL on failure for unrecognized boolean values
    FILTER_VALIDATE_BOOLEAN Validates a boolean
    FILTER_VALIDATE_EMAIL Validates value as a valid e-mail address
    FILTER_VALIDATE_FLOAT Validates value as float
    FILTER_VALIDATE_INT Validates value as integer
    FILTER_VALIDATE_IP Validates value as IP address
    FILTER_VALIDATE_MAC Validates value as MAC address
    FILTER_VALIDATE_REGEXP Validates value against a regular expression
    FILTER_VALIDATE_URL Validates value as URL
    FILTER_SANITIZE_EMAIL Removes all illegal characters from an e-mail address
    FILTER_SANITIZE_ENCODED Removes/Encodes special characters
    FILTER_SANITIZE_MAGIC_QUOTES Apply addslashes()
    FILTER_SANITIZE_NUMBER_FLOAT Remove all characters, except digits, +- signs, and optionally .,eE
    FILTER_SANITIZE_NUMBER_INT Removes all characters except digits and + - signs
    FILTER_SANITIZE_SPECIAL_CHARS Removes special characters
    FILTER_SANITIZE_STRING Removes tags/special characters from a string
    FILTER_SANITIZE_STRIPPED Alias of FILTER_SANITIZE_STRING
    FILTER_SANITIZE_URL Removes all illegal character from s URL
    FILTER_UNSAFE_RAW Do nothing, optionally strip/encode special characters
    FILTER_CALLBACK Call a user-defined function to filter data
    PHP Filter Reference

    Example

    Check if the input variable "email" is sent to the PHP page, through the "get" method: <?phpif (!filter_has_var(INPUT_GET, "email")) { echo("Email not found");} else { echo("Email found");}?> Try it Yourself »

    Definition and Usage

    The filter_has_var() function checks whether a variable of a specified input type exist. This function checks the content received by the PHP page, so the variable must be sent to the page via e.g a querystring.

    Syntax

    filter_has_var(type, variable)

    Parameter Values

    ParameterDescription
    typeRequired. The input type to check for. Can be one of the following:
  • INPUT_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_SERVER
  • INPUT_ENV
  • variableRequired. The variable name to check

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 5.2+
    Complete PHP Filter Reference PHP Filter Reference

    Example

    Return the filter ID of the VALIDATE_EMAIL filter: <?php$echo(filter_id("validate_email"));?> Try it Yourself »

    Definition and Usage

    The filter_id() function returns filter ID of a specified filter name.

    Syntax

    filter_id(filter_name)

    Parameter Values

    ParameterDescription
    filter_nameRequired. The filter name to get the id from. Tip: Use filter_list() to list all available filters

    Technical Details

    Return Value: The filter ID on success, FALSE if filter does not exist
    PHP Version: 5.2+

    More Examples

    Example

    Here, the filter_id() and the filter_list() functions are used to list the ID and filter name of all filters: <table> <tr> <td>Filter Name</td> <td>Filter ID</td> </tr> <?php foreach (filter_list() as $id =>$filter) { echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>'; }?> </table> Try it Yourself » PHP Filter Reference PHP Filter Reference

    Example

    Check if the external variable "email" is sent to the PHP page, through the "get" method, and also check if it is a valid email address: <?phpif (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) { echo("Email is not valid");} else { echo("Email is valid");}?> Try it Yourself »

    Definition and Usage

    The filter_input() function gets an external variable (e.g. from form input) and optionally filters it. This function is used to validate variables from insecure sources, such as user input.

    Syntax

    filter_input(type, variable, filter, options)

    Parameter Values

    ParameterDescription
    typeRequired. The input type to check for. Can be one of the following:
  • INPUT_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_SERVER
  • INPUT_ENV
  • variableRequired. The variable name to check
    filterOptional. Specifies the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering
    optionsOptional. Specifies one or more flags/options to use. Check each filter for possible options and flags

    Technical Details

    Return Value: The value of the variable on success, FALSE on failure, or NULL if the variable is not set
    PHP Version: 5.2+
    Complete PHP Filter Reference PHP Filter Reference

    Example

    Use the filter_input_array() function to filter three POST variables. The received POST variables is name, age and e-mail: <?php $filters = array ( "name" => array ("filter"=>FILTER_CALLBACK, "flags"=>FILTER_FORCE_ARRAY, "options"=>"ucwords" ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array("min_range"=>1,"max_range"=>120) ), "email" => FILTER_VALIDATE_EMAIL ); print_r(filter_input_array(INPUT_POST, $filters)); ?> The output of the code above will be: Array ( [name] => Peter [age] => 41 [email] => peter@example.com )

    Definition and Usage

    The filter_input_array() function gets external variables (e.g. from form input) and optionally filters them. This function is useful for retrieving/filtering many values instead of calling filter_input() many times.

    Syntax

    filter_input_array(type, definition, add_empty)

    Parameter Values

    ParameterDescription
    typeRequired. The input type to check for. Can be one of the following:
  • INPUT_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_SERVER
  • INPUT_ENV
  • definitionOptional. Specifies an array of filter arguments. A valid array key is a variable name, and a valid value is a filter name or ID, or an array specifying the filter, flags and options. This parameter can also be a single filter name/ID; then all values in the input array are filtered by the specified filter
    add_emptyOptional. A Boolean value. TRUE adds missing keys as NULL to the return value. Default value is TRUE

    Technical Details

    Return Value: An array with the values of the variables on success, FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.4 - The add_empty parameter was added
    Complete PHP Filter Reference PHP Filter Reference

    Example

    List all supported filter names: <?phpprint_r(filter_list());?> Try it Yourself »

    Definition and Usage

    The filter_list() function returns a list of all the supported filter names.

    Syntax

    filter_list()

    Technical Details

    Return Value: An array of all supported filter names, an empty array if there are no filter names
    PHP Version: 5.2+

    More Examples

    Example

    Here, the filter_id() and the filter_list() functions are used to list the ID and filter name of all filters: <table> <tr> <td>Filter Name</td> <td>Filter ID</td> </tr> <?php foreach (filter_list() as $id =>$filter) { echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>'; }?> </table> Try it Yourself » PHP Filter Reference PHP Filter Reference

    Example

    Check if $email is a valid email address: <?php$email = "john.doe@example.com";if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo("$email is a valid email address");} else { echo("$email is not a valid email address");}?> Try it Yourself »

    Definition and Usage

    The filter_var() function filters a variable with the specified filter.

    Syntax

    filter_var(var, filtername, options)

    Parameter Values

    ParameterDescription
    varRequired. The variable to filter
    filternameOptional. Specifies the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering
    optionsOptional. Specifies one or more flags/options to use. Check each filter for possible options and flags

    Technical Details

    Return Value: Returns the filtered data on success, FALSE on failure
    PHP Version: 5.2+

    More Examples

    The example below both sanitizes and validates an email address:

    Example

    First remove illegal characters from $email, then check if it is a valid email address: <?php$email = "john.doe@example.com";// Remove all illegal characters from email$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate e-mailif (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo("$email is a valid email address");} else { echo("$email is not a valid email address"); }?> Try it Yourself » PHP Filter Reference PHP Filter Reference

    Example

    Use the filter_var_array() function to get multiple variables: <?php $data = array( 'fullname' => 'Peter Griffin', 'age' => '41', 'email' => 'peter@example.com', ); $mydata = filter_var_array($data); var_dump($mydata); ?> The output of the code should be: array(3) { ["fullname"]=> string(13) "Peter Griffin" ["age"]=> string(2) "41" ["email"]=> string(17) "peter@example.com"}

    Definition and Usage

    The filter_var_array() function gets multiple variables and optionally filters them. This function is useful for filtering many values without calling filter_var() many times. Tip: Check the PHP Filter Reference for possible filters to use with this function.

    Syntax

    filter_var_array(data_array, args, add_empty)

    Parameter Values

    Parameter Description
    data_arrayRequired. Specifies an array with string keys containing the data to filter
    argsOptional. Specifies an array of filter arguments. A valid array key is a variable name and a valid value is a filter ID, or an array specifying the filter, flags and option. This parameter can also be a single filter ID, if so, all values in the input array are filtered by the specified filter. A filter ID can be an ID name (like FILTER_VALIDATE_EMAIL) or an ID number (like 274)
    add_emptyOptional. A Boolean value. TRUE adds missing keys as NULL to the return value. Default value is TRUE

    Technical Details

    Return Value: An array of values of the requested variables on success, FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 5.4 - The add_empty parameter was added
    Complete PHP Filter Reference

    FTP Introduction

    The FTP functions give client access to file servers through the File Transfer Protocol (FTP). The FTP functions are used to open, login and close connections, as well as upload, download, rename, delete, and get information on files from file servers. Not all of the FTP functions will work with every server or return the same results. The FTP functions became available with PHP 3. If you only wish to read from or write to a file on an FTP server, consider using the ftp:// wrapper with the Filesystem functions which provide a simpler and more intuitive interface.

    Installation

    For these functions to work, you have to compile PHP with --enable-ftp. The Windows version of PHP has built-in support for this extension.

    FTP Functions

    FunctionDescription
    ftp_alloc()Allocates space for a file to be uploaded to the FTP server
    ftp_cdup()Changes to the parent directory on the FTP server
    ftp_chdir()Changes the current directory on the FTP server
    ftp_chmod()Sets permissions on a file via FTP
    ftp_close()Closes an FTP connection
    ftp_connect()Opens an FTP connection
    ftp_delete()Deletes a file on the FTP server
    ftp_exec()Executes a command on the FTP server
    ftp_fget()Downloads a file from the FTP server and saves it into an open local file
    ftp_fput()Uploads from an open file and saves it to a file on the FTP server
    ftp_get()Downloads a file from the FTP server
    ftp_get_option()Returns runtime options of the FTP connection
    ftp_login()Logs in to the FTP connection
    ftp_mdtm()Returns the last modified time of a specified file
    ftp_mkdir()Creates a new directory on the FTP server
    ftp_mlsd()Returns the list of files in the specified directory
    ftp_nb_continue()Continues retrieving/sending a file (non-blocking)
    ftp_nb_fget()Downloads a file from the FTP server and saves it into an open file (non-blocking)
    ftp_nb_fput()Uploads from an open file and saves it to a file on the FTP server (non-blocking)
    ftp_nb_get()Downloads a file from the FTP server (non-blocking)
    ftp_nb_put()Uploads a file to the FTP server (non-blocking)
    ftp_nlist()Returns a list of files in the specified directory on the FTP server
    ftp_pasv()Turns passive mode on or off
    ftp_put()Uploads a file to the FTP server
    ftp_pwd()Returns the current directory name
    ftp_quit()Alias of ftp_close()
    ftp_raw()Sends a raw command to the FTP server
    ftp_rawlist()Returns a list of files with file information from a specified directory
    ftp_rename()Renames a file or directory on the FTP server
    ftp_rmdir()Deletes an empty directory on the FTP server
    ftp_set_option()Sets runtime options for the FTP connection
    ftp_site()Sends an FTP SITE command to the FTP server
    ftp_size()Returns the size of the specified file
    ftp_ssl_connect()Opens a secure SSL-FTP connection
    ftp_systype()Returns the system type identifier of the FTP server

    Predefined FTP Constants

    ConstantTypeDescription
    FTP_ASCIIInteger
    FTP_AUTOSEEKInteger
    FTP_AUTORESUMEInteger
    FTP_BINARYInteger
    FTP_FAILEDIntegerAsynchronous transfer has failed
    FTP_FINISHEDIntegerAsynchronous transfer is completed
    FTP_IMAGEIntegerAlias of FTP_BINARY
    FTP_MOREDATAIntegerAsynchronous transfer is in progress
    FTP_TEXTIntegerAlias of FTP_ASCII
    FTP_TIMEOUT_SECIntegerThe timeout used for network operations
    FTP_USEPASVADDRESSBoolean
    PHP FTP Reference

    Example

    Allocate space for a file and upload the file to the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "/test/myfile";// allocate spaceif (ftp_alloc($ftp_conn, filesize($file), $result)) { echo "Space allocated on server. Sending $file."; ftp_put($ftp_conn, "/files/myfile", $file, FTP_BINARY); }else { echo "Error! Server said: $result"; }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_alloc() function allocates space for a file to be uploaded to the FTP server. Note: Many FTP servers do not support this command!

    Syntax

    ftp_alloc(ftp_conn, filesize, result);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    filesizeRequired. Specifies the number of bytes to allocate
    resultOptional. Specifies a variable to store the server response in

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 5+
    PHP FTP Reference PHP FTP Reference

    Example

    Output current directory name, then change to parent directory: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// change the current directory to php ftp_chdir($ftp_conn, "php"); // change to the parent directoryif (ftp_cdup($ftp_conn)) { echo "Successfully changed to parent directory."; } else { echo "cdup failed."; }// output current directory nameecho ftp_pwd($ftp_conn);// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_cdup() function changes to the parent directory on the FTP server.

    Syntax

    ftp_cdup(ftp_conn);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Change directory, then output directory name: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// change the current directory to phpftp_chdir($ftp_conn, "php");// output current directory name (/php) echo ftp_pwd($ftp_conn); // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_chdir() function changes the current directory on the FTP server.

    Syntax

    ftp_chdir(ftp_conn, directory);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    directoryRequired. Specifies the directory to change to

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Set file permissions: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "php/test.txt"; // Try to set read and write for owner and read for everybody else if (ftp_chmod($ftp_conn, 0644, $file) !== false) { echo "Successfully chmoded $file to 644."; }else { echo "chmod failed."; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_chmod() function sets permissions on the specified file via FTP.

    Syntax

    ftp_chmod(ftp_conn, mode, file);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    modeRequired. Specifies the new permissions.This parameter consists of four numbers:
  • The first number is always zero
  • The second number specifies permissions for the OWNER
  • The third number specifies permissions for the OWNER's USER GROUP
  • The fourth number specifies permissions for EVERYBODY ELSE
  • Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions
  • fileRequired. Specifies the file to set permissions on

    Technical Details

    Return Value: The new file permissions on success, FALSE on failure
    PHP Version: 5+
    PHP FTP Reference PHP FTP Reference

    Example

    Connect, login, and close an FTP connection: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// then do something...// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_close() function closes an FTP connection.

    Syntax

    ftp_close(ftp_conn);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to close

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.2+
    PHP FTP Reference PHP FTP Reference

    Example

    Connect, login, and close an FTP connection: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// then do something...// close connectionftp_close($ftp_conn); ?>

    Definition and Usage

    The ftp_connect() function opens an FTP connection to the specified host. When the connection is open, you can run FTP functions against the server.

    Syntax

    ftp_connect(host, port, timeout);

    Parameter Values

    ParameterDescription
    hostRequired. Specifies the FTP server to connect to. Can be a domain address or an IP address. This parameter should not be prefixed with "ftp://" or have any trailing slashes
    portOptional. Specifies the port of the FTP server. Default is port 21
    timeoutOptional. Specifies the timeout for all subsequent network operations. Default is 90 seconds

    Technical Details

    Return Value: An FTP stream on success or FALSE on error
    PHP Version: 4+
    PHP Changelog: The timeout parameter was added in PHP 4.2.0
    PHP FTP Reference PHP FTP Reference

    Example

    Delete a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "php/test.txt";// try to delete fileif (ftp_delete($ftp_conn, $file)) { echo "$file deleted"; }else { echo "Could not delete $file"; }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_delete() function deletes a file on the FTP server.

    Syntax

    ftp_delete(ftp_conn, file);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    fileRequired. Specifies the path of the file to delete

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Request for execution of a command on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$command = "ls-al > somefile.txt"; // execute command if (ftp_exec($ftp_conn,$command)) { echo "$command executed successfully."; } else { echo "Execution of $command failed."; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_exec() function requests for execution of a command on the FTP server.

    Syntax

    ftp_exec(ftp_conn, command);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    commandRequired. Specifies the command to execute

    Technical Details

    Return Value: TRUE if the command was executed successfully; FALSE otherwise
    PHP Version: 4.0.3+
    PHP FTP Reference PHP FTP Reference

    Example

    Download a file from the FTP server, and save it to an open local file: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$server_file = "somefile.txt";// open local file to write to$local_file = "local.txt";$fp = fopen($local_file,"w");// download server file and save it to open local fileif (ftp_fget($ftp_conn, $fp, $server_file, FTP_ASCII, 0)) { echo "Successfully written to $local_file."; }else { echo "Error downloading $server_file."; }// close connection and file handlerftp_close($ftp_conn);fclose($fp);?>

    Definition and Usage

    The ftp_fget() function gets (downloads) a file from the FTP server, and saves it into an open local file.

    Syntax

    ftp_fget(ftp_conn, open_file, server_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    open_fileRequired. Specifies an open local file in which we store the data
    server_fileRequired. Specifies the server file to download
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start downloading from

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.PHP 4.3 - The startpos parameter was added.
    PHP FTP Reference PHP FTP Reference

    Example

    Open local file, and upload it to a file on the FTP server: <?php // connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// open file for reading$file = "test.txt";$fp = fopen($file,"r");// upload fileif (ftp_fput($ftp_conn, "somefile.txt", $fp, FTP_ASCII)) { echo "Successfully uploaded $file."; }else { echo "Error uploading $file."; }// close this connection and file handlerftp_close($ftp_conn); fclose($fp);?>

    Definition and Usage

    The ftp_fput() function uploads from an open file and saves it to a file on the FTP server.

    Syntax

    ftp_fput(ftp_conn, remote_file, open_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    remote_fileRequired. Specifies the file path to upload to
    open_fileRequired. Specifies an open local file. Reading stops at end of file
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start uploading to

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.PHP 4.3 - The startpos parameter was added.
    PHP FTP Reference PHP FTP Reference

    Example

    Download a file from the FTP server, and save it into a local file: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$local_file = "local.zip";$server_file = "server.zip";// download server fileif (ftp_get($ftp_conn, $local_file, $server_file, FTP_ASCII)) { echo "Successfully written to $local_file."; }else { echo "Error downloading $server_file."; }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_get() function gets (downloads) a file from the FTP server, and saves it into a local file.

    Syntax

    ftp_get(ftp_conn, local_file, server_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    local_fileRequired. Specifies the local file path (will be overwritten if the file already exists)
    server_fileRequired. Specifies the server file to download
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start downloading from

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.PHP 4.3 - The startpos parameter was added.
    PHP FTP Reference PHP FTP Reference

    Example

    Return the timeout used for network operations: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// could return 90echo ftp_get_option($ftp_conn,FTP_TIMEOUT_SEC); // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_get_option() function returns runtime options of the current FTP connection.

    Syntax

    ftp_get_option(ftp_conn, option);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    optionRequired. Specifies the runtime option to return. Possible values:
  • FTP_TIMEOUT_SEC - Returns the timeout used for network operations
  • FTP_AUTOSEEK - Returns TRUE if this option is on, FALSE otherwise
  • Technical Details

    Return Value: Returns the value on success, or FALSE (and a warning message) if the given option is not supported
    PHP Version: 4.2+
    PHP FTP Reference PHP FTP Reference

    Example

    Connect, login, and close an FTP connection: <?php// connect to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");// loginif (@ftp_login($ftp_conn, $ftp_username, $ftp_userpass)) { echo "Connection established."; }else { echo "Couldn't establish a connection."; }// do something...// close connectionftp_close($ftp_conn); ?>

    Definition and Usage

    The ftp_login() function logs in to the specified FTP connection.

    Syntax

    ftp_login(ftp_conn, username, password);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    usernameRequired. Specifies the username to login with
    passwordRequired. Specifies the password to login with

    Technical Details

    Return Value: TRUE on success, FALSE and a warning on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Get last modified time for a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "somefile.txt"; // get the last modified time$lastchanged = ftp_mdtm($ftp_conn, $file);if ($lastchanged != -1) { echo "$file was last modified on : " . date("F d Y H:i:s.",$lastchanged); } else { echo "Could not get last modified"; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_mdtm() function returns when the specified file was last modified. Note: Not all servers support this function, and this function does not work with directories.

    Syntax

    ftp_mdtm(ftp_conn, file);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to login to
    fileRequired. Specifies the file to check

    Technical Details

    Return Value: The last modified time as a Unix timestamp on success, -1 on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Create a new directory on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$dir = "images"; // try to create directory $dirif (ftp_mkdir($ftp_conn, $dir)) { echo "Successfully created $dir"; }else { echo "Error while creating $dir"; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_mkdir() function creates a new directory on the FTP server.

    Syntax

    ftp_mkdir(ftp_conn, dir);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    dirRequired. Specifies the name of the directory to create

    Technical Details

    Return Value: The name of the new directory on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Returns the list of files from the "images" directory: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$dir = "/images"; $dirlist = ftp_mlsd($ftp_conn, $dir);// output directory listecho($dirlist); // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_mlsd() function returns the list of files in the specified directory.

    Syntax

    ftp_mlsd(ftp_conn, dir);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    dirRequired. Specifies the name of the directory to be listed. Use "." to get the current directory

    Technical Details

    Return Value: An array with file info from the specified directory on success, FALSE on failure
    PHP Version: 7.2+
    PHP FTP Reference PHP FTP Reference

    Example

    Download a file from the server, continue downloading (non-blocking) while doing something else: <?php// initiate download$d = ftp_nb_get($ftp_conn, "local.txt", "server.txt", FTP_BINARY)while ($d == FTP_MOREDATA) { // do whatever you want // continue downloading $d = ftp_nb_continue($ftp_conn); } if ($d != FTP_FINISHED) { echo "Error downloading file."; exit(1); }?>

    Definition and Usage

    The ftp_nb_continue() function continues to receive/send a file to the FTP server.

    Syntax

    ftp_nb_continue(ftp_conn);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use

    Technical Details

    Return Value: One of the following values:
  • FTP_FAILED (send/receive failed)
  • FTP_FINISHED (send/receive completed)
  • FTP_MOREDATA (send/receive in progress)
  • PHP Version: 4.3+
    PHP FTP Reference PHP FTP Reference

    Example

    Download a file from the FTP server, and save it to an open local file (non-blocking): <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$server_file = "somefile.txt";// open local file to write to$local_file = "local.txt";$fp = fopen($local_file,"w");// initiate download$d = ftp_nb_fget($ftp_conn, $fp, $server_file, FTP_BINARY)while ($d == FTP_MOREDATA) { // do whatever you want // continue downloading $d = ftp_nb_continue($ftp_conn); } if ($d != FTP_FINISHED) { echo "Error downloading $server_file"; exit(1); }// close connection and file handlerftp_close($ftp_conn);fclose($fp);?>

    Definition and Usage

    The ftp_nb_fget() function gets (downloads) a file from the FTP server, and saves it into an open local file (non-blocking). Tip: This function (as opposite to ftp_fget()) retrieves the file asynchronously, so you can perform other operations while the file is being downloaded.

    Syntax

    ftp_nb_fget(ftp_conn, open_file, server_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    open_fileRequired. Specifies an open local file in which we store the data
    server_fileRequired. Specifies the server file to download
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start downloading from

    Technical Details

    Return Value: One of the following values:
  • FTP_FAILED (send/receive failed)
  • FTP_FINISHED (send/receive completed)
  • FTP_MOREDATA (send/receive in progress)
  • PHP Version: 4.3+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.
    PHP FTP Reference PHP FTP Reference

    Example

    Open local file, and upload it (non-blocking) to a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$server_file = "serverfile.txt";// open local file$local_file = "localfile.txt";$fp = fopen($local_file,"r");// initiate upload$d = ftp_nb_fput($ftp_conn, $server_file, $fp, FTP_BINARY)while ($d == FTP_MOREDATA) { // do whatever you want // continue uploading $d = ftp_nb_continue($ftp_conn); } if ($d != FTP_FINISHED) { echo "Error uploading $local_file"; exit(1); }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_nb_fput() function uploads an open local file to the FTP server (non-blocking). Tip: This function (as opposite to ftp_fput()) retrieves the file asynchronously, so you can perform other operations while the file is being downloaded.

    Syntax

    ftp_nb_fput(ftp_conn, remote_file, open_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    remote_fileRequired. Specifies the file path to upload to
    open_fileRequired. Specifies a pointer to the open local file
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start uploading to

    Technical Details

    Return Value: One of the following values:
  • FTP_FAILED (send/receive failed)
  • FTP_FINISHED (send/receive completed)
  • FTP_MOREDATA (send/receive in progress)
  • PHP Version: 4.3+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.
    PHP FTP Reference PHP FTP Reference

    Example

    Download a file from the FTP server, and save it into a local file (non-blocking): <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$local_file = "local.zip";$server_file = "server.zip";// initiate download$d = ftp_nb_get($ftp_conn, $local_file, $server_file, FTP_ASCII)while ($d == FTP_MOREDATA) { // do whatever you want // continue downloading $d = ftp_nb_continue($ftp_conn); } if ($d != FTP_FINISHED) { echo "Error downloading $server_file"; exit(1); }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_nb_get() function gets (downloads) a file from the FTP server, and saves it into a local file (non-blocking). Tip: This function (as opposite to ftp_get()) retrieves the file asynchronously, so you can perform other operations while the file is being downloaded.

    Syntax

    ftp_nb_get(ftp_conn, local_file, server_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    local_fileRequired. Specifies the local file path (will be overwritten if the file already exists)
    server_fileRequired. Specifies the server file to download
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start downloading from

    Technical Details

    Return Value: One of the following values:
  • FTP_FAILED (send/receive failed)
  • FTP_FINISHED (send/receive completed)
  • FTP_MOREDATA (send/receive in progress)
  • PHP Version: 4.3+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.
    PHP FTP Reference PHP FTP Reference

    Example

    Upload local file (non-blocking) to a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$local_file = "localfile.txt";$server_file = "serverfile.txt";// initiate upload$d = ftp_nb_put($ftp_conn, $server_file, $local_file, FTP_BINARY)while ($d == FTP_MOREDATA) { // do whatever you want // continue uploading $d = ftp_nb_continue($ftp_conn); } if ($d != FTP_FINISHED) { echo "Error uploading $local_file"; exit(1); }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_nb_put() function uploads a file to the FTP server (non-blocking). Tip: This function (as opposite to ftp_put()) retrieves the file asynchronously, so you can perform other operations while the file is being downloaded.

    Syntax

    ftp_nb_put(ftp_conn, remote_file, local_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    remote_fileRequired. Specifies the file path to upload to
    local_fileRequired. Specifies the path of the local file to upload
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start uploading to

    Technical Details

    Return Value: One of the following values:
  • FTP_FAILED (send/receive failed)
  • FTP_FINISHED (send/receive completed)
  • FTP_MOREDATA (send/receive in progress)
  • PHP Version: 4.3+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.
    PHP FTP Reference PHP FTP Reference

    Example

    List files in current directory: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// get file list of current directory$file_list = ftp_nlist($ftp_conn, ".");var_dump($file_list);// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_nlist() function returns a list of files in the specified directory on the FTP server.

    Syntax

    ftp_nlist(ftp_conn, dir);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    dirRequired. Specifies the directory to be listed. Use "." to get the current directory

    Technical Details

    Return Value: An array of file names from the specified directory on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Turn passive mode on and upload a file to the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// turn passive mode onftp_pasv($ftp_conn, true);$file = "localfile.txt";// upload fileif (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII)) { echo "Successfully uploaded $file."; }else { echo "Error uploading $file."; }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_pasv() function turns passive mode on or off. In passive mode, data connections are initiated by the client, not the server. This is useful if the client is behind a firewall.

    Syntax

    ftp_pasv(ftp_conn, pasv);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    pasvRequired. Specifies the passive mode. Possible values:
  • TRUE (passive mode on)
  • FALSE (passive mode off)
  • Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Upload local file to a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "localfile.txt";// upload fileif (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII)) { echo "Successfully uploaded $file."; }else { echo "Error uploading $file."; }// close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_put() function uploads a file to the FTP server.

    Syntax

    ftp_put(ftp_conn, remote_file, local_file, mode, startpos);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    remote_fileRequired. Specifies the file path to upload to
    local_fileRequired. Specifies the path of the file to upload
    modeOptional. Specifies the transfer mode. Possible values: FTP_ASCII or FTP_BINARY
    startposOptional. Specifies the position in the remote file to start uploading to

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 7.3 - The mode parameter was made optional.PHP 4.3 - The startpos parameter was added.
    PHP FTP Reference PHP FTP Reference

    Example

    Change directory, then output directory name: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// change the current directory to phpftp_chdir($ftp_conn, "php");// output current directory name (/php) echo ftp_pwd($ftp_conn); // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_pwd() function returns the current directory name.

    Syntax

    ftp_pwd(ftp_conn);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use

    Technical Details

    Return Value: The current directory name on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Definition and Usage

    The ftp_quit() function is an alias of ftp_close(). PHP FTP Reference PHP FTP Reference

    Example

    Connect to FTP server and execute commands: <?php// connect to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");// the two lines below is the same as: ftp_login($ftp_conn,"john","secretpassword"); ftp_raw($ftp_conn, "USER john");ftp_raw($ftp_conn, "PASS secretpassword");?>

    Definition and Usage

    The ftp_raw() function sends a raw command to the FTP server.

    Syntax

    ftp_raw(ftp_conn, command);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    commandRequired. Specifies the command to execute

    Technical Details

    Return Value: The response from the server as an array of strings
    PHP Version: 5+
    PHP FTP Reference PHP FTP Reference

    Example

    Get list of files with file information: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// get the file list for /$filelist = ftp_rawlist($ftp_conn, "/");// close connectionftp_close($ftp_conn); // output $filelistvar_dump($filelist);?> The output could look something like this: array(3) { [0] => string(57) "drw-rw-rw- 1 user group 0 Jan 03 08:33 images" [1] => string(62) "-rw-rw-rw- 1 user group 160 Feb 16 13:54 php" [2] => string(75) "-rw-rw-rw- 1 user group 20 Feb 14 12:22 test" }

    Definition and Usage

    The ftp_rawlist() function returns a list of files with file information (from a specified directory on the FTP server).

    Syntax

    ftp_rawlist(ftp_conn, dir, recursive);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    dirRequired. Specifies the directory path. May include arguments for the LIST command. Tip: Use "." to specify the current directory
    recursiveOptional. By default, this function sends a "LIST" command to the server. However, if the recursive parameter is set to TRUE, it sends a "LIST -R" command

    Technical Details

    Return Value: An array where each element corresponds to one line of text (no parsing is performed). Returns FALSE on failure
    PHP Version: 4+
    PHP Changelog: The recursive parameter was added in PHP 4.3
    PHP FTP Reference PHP FTP Reference

    Example

    Rename a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$old_file = "oldfile.txt"; $new_file = "newfile.txt";// try to rename $old_file to $new_file if (ftp_rename($ftp_conn, $old_file, $new_file)) { echo "Renamed $old_file to $new_file"; }else { echo "Problem renaming $old_file to $new_file"; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_rename() function renames a file or directory on the FTP server.

    Syntax

    ftp_rename(ftp_conn, oldname, newname);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    oldnameRequired. Specifies the file or directory to rename
    newnameRequired. Specifies the new name of the file or directory

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Delete a directory on FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$dir = "php/"; // try to delete $dir if (ftp_rmdir($ftp_conn, $dir)) { echo "Directory $dir deleted"; }else { echo "Problem deleting $dir"; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_rmdir() function deletes a directory on the FTP server. Note: A directory must be empty before it can be deleted! Tip: Use the ftp_mkdir() function to create a new directory.

    Syntax

    ftp_rmdir(ftp_conn, dir);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    dirRequired. Specifies the empty directory to delete

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Set timeout for network operations: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// set network operation timeout to 120 secondsecho ftp_set_option($ftp_conn,FTP_TIMEOUT_SEC,120); // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_set_option() function sets runtime options of the current FTP connection.

    Syntax

    ftp_set_option(ftp_conn, option, value);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    optionRequired. Specifies the runtime option to set. Possible values:
  • FTP_TIMEOUT_SEC
  • FTP_AUTOSEEK
  • FTP_USEPASVADDRESS
  • valueRequired. Specifies the value of the option parameter

    Technical Details

    Return Value: TRUE if the option could be set, FALSE if not (a warning message is also thrown)
    PHP Version: 4.2+
    PHP FTP Reference PHP FTP Reference

    Example

    Send an FTP SITE command: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// try to send SITE command if (ftp_site($ftp_conn, "chmod 777 serverfile.txt")) { echo "Command executed successfully"; }else { echo "Command failed"; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_site() function sends a SITE command to the FTP server. Note: SITE commands vary from server to server. They are useful for handling OS specific features such as file permissions and group membership. Tip: To see what SITE commands are available, send the REMOTEHELP command using the ftp_raw() function.

    Syntax

    ftp_site(ftp_conn, command);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    commandRequired. Specifies the SITE command (this parameter is not escaped)

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Get size of a file on the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);$file = "serverfile.txt"; // get size of $file$fsize = ftp_size($ftp_conn, $file);if ($fsize != -1) { echo "$file is $fsize bytes."; }else { echo "Error getting file size."; } // close connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_size() function returns the size of a specified file on the FTP server. Note: Not all FTP servers support this function!

    Syntax

    ftp_size(ftp_conn, file);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use
    fileRequired. Specifies the server file to check

    Technical Details

    Return Value: The size of the file (in bytes) on success, or -1 on error
    PHP Version: 4+
    PHP FTP Reference PHP FTP Reference

    Example

    Open a secure SSL-FTP connection: <?php// set up basic SSL connection$ftp_server = "123.123.123.123"; $ftp_conn = ftp_ssl_connect($ftp_server) or die("Could not connect to $ftp_server");// login$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// then do something... // close SSL connectionftp_close($ftp_conn);?>

    Definition and Usage

    The ftp_ssl_connect() function opens a secure SSL-FTP connection. When the connection is open, you can run FTP functions against the server. Note: This function is only available if both the ftp module and the OpenSSL support is built statically into PHP.

    Syntax

    ftp_ssl_connect(host, port, timeout);

    Parameter Values

    ParameterDescription
    hostRequired. Specifies the FTP server address. Can be a domain address or an IP address. This parameter should not be prefixed with "ftp://" or have any trailing slashes
    portOptional. Specifies the port to connect to. Default is 21
    timeoutOptional. Specifies the timeout for network operations. Default is 90 seconds

    Technical Details

    Return Value: An SSL-FTP stream on success, FALSE on failure
    PHP Version: 4.3+
    PHP Changelog: PHP 5.2.2 - This function returns FALSE if it cannot use an SSL connection, instead of falling back to a non-SSL connection
    PHP FTP Reference PHP FTP Reference

    Example

    Get the system type of the FTP server: <?php// connect and login to FTP server $ftp_server = "ftp.example.com";$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);// get system typeif ($type = ftp_systype($ftp_conn)) { echo "System type is: $type"; }else { echo "Could not get system type."; }// close connectionftp_close($ftp_conn);?> The output could look something like this: System type is: UNIX

    Definition and Usage

    The ftp_systype() function returns the system type identifier of the FTP server.

    Syntax

    ftp_systype(ftp_conn);

    Parameter Values

    ParameterDescription
    ftp_connRequired. Specifies the FTP connection to use

    Technical Details

    Return Value: The system type on success, FALSE on failure
    PHP Version: 4+
    PHP FTP Reference

    JSON Introduction

    The JSON extension implements the JavaScript Object Notation data-interchange format. In PHP 5, the decoding is handled by a parser based on the JSON_checker by Douglas Crockford. PHP 7 has a new and improved parser specifically written for PHP and licensed under the PHP license.

    Installation

    From PHP 5.2.0, the JSON functions are enabled by default. There is no installation needed to use these functions.

    JSON Functions

    FunctionDescription
    json_decode()Decodes a JSON string
    json_encode()Encode a value to JSON format
    json_last_error()Returns the last error occurred
    json_last_error_msg()Returns the error string of the last json_encode() or json_decode() call

    Predefined JSON Constants

    ConstantTypeDescription
    JSON_ERROR_NONEIntegerNo error has occurred
    JSON_ERROR_DEPTHIntegerMaximum stack depth has been exceeded
    JSON_ERROR_STATE_MISMATCHIntegerInvalid/Malformed JSON
    JSON_ERROR_CTRL_CHARIntegerControl character error
    JSON_ERROR_SYNTAXIntegerSyntax error
    JSON_ERROR_UTF8IntegerMalformed UTF-8 characters. PHP 5.3
    JSON_ERROR_RECURSIONIntegerInvalid recursive reference values. PHP 5.5
    JSON_ERROR_INF_OR_NANIntegerInvalid NAN or INF values. PHP 5.5
    JSON_ERROR_UNSUPPORTED_TYPEIntegerInvalid type. PHP 5.5
    JSON_ERROR_INVALID_PROPERTY_NAMEIntegerInvalid property name. PHP 7.0
    JSON_ERROR_UTF16IntegerMalformed UTF-16 characters. PHP 7.0
    JSON_BIGINT_AS_STRINGInteger
    JSON_OBJECT_AS_ARRAYInteger
    JSON_HEX_TAGInteger
    JSON_HEX_AMPInteger
    JSON_HEX_APOSInteger
    JSON_HEX_QUOTInteger
    JSON_FORCE_OBJECTInteger
    JSON_NUMERIC_CHECKInteger
    JSON_PRETTY_PRINTInteger
    JSON_UNESCAPED_SLASHESInteger
    JSON_PARTIAL_OUTPUT_ON_ERRORInteger
    JSON_PRESERVE_ZERO_FRACTIONInteger
    JSON_UNESCAPED_LINE_TERMINATORSInteger
    JSON_INVALID_UTF8_IGNOREInteger
    JSON_INVALID_UTF8_SUBSTITUTEInteger
    JSON_THROWN_ON_ERRORInteger
    PHP JSON Reference

    Example

    Store JSON data in a PHP variable, and then decode it into a PHP object: <?php$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';var_dump(json_decode($jsonobj));?> Run Example »

    Definition and Usage

    The json_decode() function is used to decode or convert a JSON object to a PHP object.

    Syntax

    json_decode(string, assoc, depth, options)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the value to be encoded
    assocOptional. Specifies a Boolean value. When set to true, the returned object will be converted into an associative array. When set to false, it returns an object. False is default
    depthOptional. Specifies the recursion depth. Default recursion depth is 512
    optionsOptional. Specifies a bitmask (JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR)

    Technical Details

    Return Value: Returns the value encoded in JSON in appropriate PHP type. If the JSON object cannot be decoded it returns NULL
    PHP Version: 5.2+
    PHP Changelog: PHP 7.3: Added JSON_THROWN_ON_ERROR optionPHP 7.2: Added JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE optionsPHP 5.4: Added JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY optionsPHP 5.4: Added options parameterPHP 5.3: Added depth parameter

    More Examples

    Example

    Store JSON data in a PHP variable, and then decode it into a PHP associative array: <?php$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';var_dump(json_decode($jsonobj, true));?> Run Example »

    Example

    How to access the values from the PHP object: <?php$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}'; $obj = json_decode($jsonobj);echo $obj->Peter;echo $obj->Ben; echo $obj->Joe;?> Run Example »

    Example

    How to access the values from the PHP associative array: <?php$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}'; $arr = json_decode($jsonobj, true);echo $arr["Peter"];echo $arr["Ben"]; echo $arr["Joe"];?> Run Example » PHP JSON Reference PHP JSON Reference

    Example

    How to encode an associative array into a JSON object: <?php$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43); echo json_encode($age);?> Run Example »

    Definition and Usage

    The json_encode() function is used to encode a value to JSON format.

    Syntax

    json_encode(value, options, depth)

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to be encoded
    optionsOptional. Specifies a bitmask (JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR)
    depthOptional. Specifies the maximum depth

    Technical Details

    Return Value: Returns a JSON encoded string on success. FALSE on failure
    PHP Version: 5.2+
    PHP Changelog: PHP 7.3: Added JSON_THROWN_ON_ERROR optionPHP 7.2: Added JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE optionsPHP 7.1: Added JSON_UNESCAPED_LINE_TERMINATORS optionPHP 5.6: Added JSON_PRESERVE_ZERO_FRACTION optionPHP 5.5: Added depth parameter PHP 5.5: Added JSON_PARTIAL_OUTPUT_ON_ERROR option PHP 5.5: Changed return value on failure from null to FALSE PHP 5.4: Added JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE optionsPHP 5.3: Added JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, and JSON_NUMERIC_CHECK optionsPHP 5.3: Added options parameter

    More Examples

    Example

    How to encode an indexed array into a JSON array: <?php$cars = array("Volvo", "BMW", "Toyota");echo json_encode($cars);?> Run Example » PHP JSON Reference PHP JSON Reference

    Example

    Return the last error occurred: <?php// An invalid json string$string = "{'Peter':35,'Ben':37,'Joe':43}";echo "Decoding: " . $string; json_decode($string);echo "<br>Error: ";switch (json_last_error()) { case JSON_ERROR_NONE: echo "No errors"; break; case JSON_ERROR_DEPTH: echo "Maximum stack depth exceeded"; break; case JSON_ERROR_STATE_MISMATCH: echo "Invalid or malformed JSON"; break; case JSON_ERROR_CTRL_CHAR: echo "Control character error"; break; case JSON_ERROR_SYNTAX: echo "Syntax error"; break; case JSON_ERROR_UTF8: echo "Malformed UTF-8 characters"; break; default: echo "Unknown error"; break;}?> Run Example »

    Definition and Usage

    The json_last_error() function returns the last error occurred.

    Syntax

    json_last_error()

    Parameter Values

    NONE.

    Technical Details

    Return Value: Returns an integer, and the value can be one of the following constants:
  • JSON_ERROR_NONE (no error has occurred)
  • JSON_ERROR_DEPTH (maximum stack depth has been exceeded)
  • JSON_ERROR_STATE_MISMATCH (Invalid/Malformed JSON)
  • JSON_ERROR_CTRL_CHAR (Control character error)
  • JSON_ERROR_SYNTAX (Syntax error)
  • JSON_ERROR_UTF8 (Malformed UTF-8 characters. PHP 5.3)
  • JSON_ERROR_RECURSION (Invalid recursive reference values. PHP 5.5)
  • JSON_ERROR_INF_OR_NAN (Invalid nan or inf values. PHP 5.5)
  • JSON_ERROR_UNSUPPORTED_TYPE (Invalid type. PHP 5.5)
  • JSON_ERROR_INVALID_PROPERTY_NAME (Invalid property name. PHP 7.0)
  • JSON_ERROR_UTF16 (Malformed UTF-16 characters. PHP 7.0)
  • PHP Version: 5.3+
    PHP JSON Reference

    libxml Introduction

    The libxml functions and constants are used together with SimpleXML, XSLT and DOM functions.

    Installation

    These functions require the libxml package. Download at xmlsoft.org

    libxml Functions

    PHP: indicates the earliest version of PHP that supports the function.
    FunctionDescription
    libxml_clear_errors()Clears the libxml error buffer
    libxml_disable_entity_loader()Enables the ability to load external entities
    libxml_get_errors()Gets the errors from the the libxml error buffer
    libxml_get_last_error()Gets the last error from the the libxml error buffer
    libxml_set_external_entity_loader()Changes the default external entity loader
    libxml_set_streams_context()Sets the streams context for the next libxml document load or write
    libxml_use_internal_errors()Disables the standard libxml errors and enables user error handling

    Predefined libxml Constants

    ConstantDescription
    LIBXML_BIGLINESMake line numbers greater than 65535 to be reported correctly
    LIBXML_COMPACTSet small nodes allocation optimization. This may improve the application performance
    LIBXML_DTDATTRSet default DTD attributes
    LIBXML_DTDLOADLoad external subset
    LIBXML_DTDVALIDValidate with the DTD
    LIBXML_HTML_NOIMPLIEDSet HTML_PARSE_NOIMPLIED flag. This turns off automatic adding of implied html/body elements
    LIBXML_HTML_NODEFDTDSet HTML_PARSE_NODEFDTD flag. This prevents a default doctype to be added, if no doctype is found
    LIBXML_NOBLANKSRemove blank nodes
    LIBXML_NOCDATASet CDATA as text nodes
    LIBXML_NOEMPTYTAGChange empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
    LIBXML_NOENTSubstitute entities
    LIBXML_NOERRORDo not show error reports
    LIBXML_NONETStop network access while loading documents
    LIBXML_NOWARNINGDo not show warning reports
    LIBXML_NOXMLDECLDrop the XML declaration when saving a document
    LIBXML_NSCLEANRemove excess namespace declarations
    LIBXML_PARSEHUGESet XML_PARSE_HUGE flag. This relaxes any hardcoded limit from the parser, such as maximum depth of a document or the size of text nodes
    LIBXML_PEDANTICSet XML_PARSE_PEDANTIC flag. This enables pedantic error reporting
    LIBXML_XINCLUDEUse XInclude substitution
    LIBXML_ERR_ERRORGet recoverable errors
    LIBXML_ERR_FATALGet fatal errors
    LIBXML_ERR_NONEGet no errors
    LIBXML_ERR_WARNINGGet simple warnings
    LIBXML_VERSIONGet libxml version (e.g. 20605 or 20617)
    LIBXML_DOTTED_VERSIONGet dotted libxml version (e.g. 2.6.5 or 2.6.17)
    LIBXML_SCHEMA_CREATECreate default or fixed value nodes during XSD schema validation
    PHP libxml Reference

    Example

    Clear the libxml error buffer: <?php libxml_clear_errors() ?>

    Definition and Usage

    The libxml_clear_errors() function clears the libxml error buffer.

    Syntax

    libxml_clear_errors()

    Technical Details

    Return Value: No value
    PHP Version: 5.1+
    PHP libxml Reference PHP libxml Reference

    Example

    Enable the ability to load external entities: <?php libxml_disable_entity_loader(false) ?>

    Definition and Usage

    The libxml_disable_entity_loader() function enables the ability to load external entities.

    Syntax

    libxml_disable_entity_loader(bool)

    Parameter Values

    ParameterDescription
    boolOptional. Disable (TRUE) or enable (FALSE) libxml extensions to load external entities. Default is TRUE

    Technical Details

    Return Value: Returns the previous value of the bool parameter
    PHP Version: 5.2.11+
    PHP libxml Reference PHP libxml Reference

    Example

    Get the errors from the libxml error buffer: <?php libxml_get_errors() ?>

    Definition and Usage

    The libxml_get_errors() function gets the errors from the the libxml error buffer.

    Syntax

    libxml_get_errors()

    Technical Details

    Return Value: Returns an array of error objects, or an empty array if there are no errors in the error buffer
    PHP Version: 5.1+
    PHP libxml Reference PHP libxml Reference

    Example

    Get the last error from the libxml error buffer: <?php libxml_get_last_error() ?>

    Definition and Usage

    The libxml_get_last_error() function gets the last error from the libxml error buffer.

    Syntax

    libxml_get_last_error()

    Technical Details

    Return Value: Returns an error object if there is any error in the buffer, FALSE otherwise
    PHP Version: 5.1+
    PHP libxml Reference PHP libxml Reference

    Example

    Change the default external entity loader: <?php$xml = <<<XML<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar"> <foo>bar</foo>XML;$dtd = <<<DTD<!ELEMENT foo (#PCDATA)> DTD;libxml_set_external_entity_loader( function ($public, $system, $context) use($dtd) { var_dump($public); var_dump($system); var_dump($context); $f = fopen("php://temp", "r+"); fwrite($f, $dtd); rewind($f); return $f; });$dd = new DOMDocument;$r = $dd->loadXML($xml);var_dump($dd->validate()); ?>

    Definition and Usage

    The libxml_set_external_entity_loader() function changes the default external entity loader.

    Syntax

    libxml_set_external_entity_loader(function)

    Parameter Values

    ParameterDescription
    functionRequired. A function that takes three arguments. Two strings, a public id and system id, and a context (an array with four keys) as the third argument. This callback should return a resource, a string from which a resource can be opened, or NULL.

    Technical Details

    Return Value: Returns TRUE on success, FALSE on failure
    PHP Version: 5.4+
    PHP libxml Reference PHP libxml Reference

    Example

    Change the default external entity loader: <?php$xml = <<<XML<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar"> <foo>bar</foo>XML;$dtd = <<<DTD<!ELEMENT foo (#PCDATA)> DTD;libxml_set_external_entity_loader( function ($public, $system, $context) use($dtd) { var_dump($public); var_dump($system); var_dump($context); $f = fopen("php://temp", "r+"); fwrite($f, $dtd); rewind($f); return $f; });$dd = new DOMDocument;$r = $dd->loadXML($xml);var_dump($dd->validate()); ?>

    Definition and Usage

    The libxml_set_streams_context() function sets the streams context for the next libxml document load or write.

    Syntax

    libxml_set_streams_context(function)

    Parameter Values

    ParameterDescription
    functionRequired. A function that takes three arguments. Two strings, a public id and system id, and a context (an array with four keys) as the third argument. This callback should return a resource, a string from which a resource can be opened, or NULL.

    Technical Details

    Return Value: Nothing
    PHP Version: 5+
    PHP libxml Reference PHP libxml Reference

    Example

    Enable user error handling: <?php libxml_use_internal_errors(true) ?>

    Definition and Usage

    The libxml_use_internal_errors() function disables the standard libxml errors and enables user error handling.

    Syntax

    libxml_use_internal_errors(user_errors)

    Parameter Values

    ParameterDescription
    user_errorsOptional. Enable user error handling (TRUE) or disable user error handling (FALSE). Default is FALSE

    Technical Details

    Return Value: Returns the previous value of the user_errors parameter
    PHP Version: 5.1+
    PHP libxml Reference

    Mail Introduction

    The mail() function allows you to send emails directly from a script.

    Requirements

    For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.

    Installation

    The mail functions are part of the PHP core. There is no installation needed to use these functions.

    Runtime Configuration

    The behavior of the mail functions is affected by settings in php.ini:
    NameDefaultDescriptionChangeable
    mail.add_x_header"0"Add X-PHP-Originating-Script that will include UID of the script followed by the filename. For PHP 5.3.0 and abovePHP_INI_PERDIR
    mail.logNULLThe path to a log file that will log all mail() calls. Log include full path of script, line number, To address and headers. For PHP 5.3.0 and above PHP_INI_PERDIR
    SMTP"localhost"Windows only: The DNS name or IP address of the SMTP serverPHP_INI_ALL
    smtp_port"25"Windows only: The SMTP port number. For PHP 4.3.0 and abovePHP_INI_ALL
    sendmail_fromNULLWindows only: Specifies the "from" address to be used when sending mail from mail()PHP_INI_ALL
    sendmail_path"/usr/sbin/sendmail -t -i"Specifies where the sendmail program can be found. This directive works also under Windows. If set, SMTP, smtp_port and sendmail_from are ignored PHP_INI_SYSTEM

    Mail Functions

    FunctionDescription
    ezmlm_hash()Calculates the hash value needed by EZMLM
    mail()Allows you to send emails directly from a script
    PHP Mail Reference

    Example

    Calculate the hash value for an email address: <?php$user = "someone@example.com";$hash = ezmlm_hash($user); echo "The hash value for $user is: $hash.";?>

    Definition and Usage

    The ezmlm_hash() function calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database. This function accepts an email address, for which it calculates an integer hash value. This value is compatible with the EZMLM mailing list manager, and can then be used with the EZMLM database for user management.

    Syntax

    ezmlm_hash(address);

    Parameter Values

    ParameterDescription
    addressRequired. Specifies the email address being hashed

    Technical Details

    Return Value: Returns the hash value of the address parameter, or FALSE on failure
    PHP Version: 4.0.2+
    PHP Mail Reference PHP Mail Reference

    Example

    Send a simple email: <?php// the message$msg = "First line of text\nSecond line of text"; // use wordwrap() if lines are longer than 70 characters $msg = wordwrap($msg,70); // send email mail("someone@example.com","My subject",$msg);?>

    Definition and Usage

    The mail() function allows you to send emails directly from a script.

    Syntax

    mail(to,subject,message,headers,parameters);

    Parameter Values

    ParameterDescription
    toRequired. Specifies the receiver / receivers of the email
    subjectRequired. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
    messageRequired. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters. Windows note: If a full stop is found on the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot: <?php $txt = str_replace("\n.", "\n..", $txt); ?>
    headersOptional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n). Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.
    parametersOptional. Specifies an additional parameter to the sendmail program (the one defined in the sendmail_path configuration setting). (i.e. this can be used to set the envelope sender address when using sendmail with the -f sendmail option)

    Technical Details

    Return Value: Returns the hash value of the address parameter, or FALSE on failure. Note: Keep in mind that even if the email was accepted for delivery, it does NOT mean the email is actually sent and received!
    PHP Version: 4+
    PHP Changelog: PHP 7.2: The headers parameter also accepts an arrayPHP 5.4: Added header injection protection for the headers parameter.PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive.PHP 4.2.3: The parameter parameter is disabled in safe modePHP 4.0.5: The parameter parameter was added

    More Examples

    Send an email with extra headers: <?php $to = "somebody@example.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: somebodyelse@example.com"; mail($to,$subject,$txt,$headers); ?> Send an HTML email: <?php $to = "somebody@example.com, somebodyelse@example.com"; $subject = "HTML email"; $message = " <html> <head> <title>HTML email</title> </head> <body> <p>This email contains HTML Tags!</p> <table> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>John</td> <td>Doe</td> </tr> </table> </body> </html> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <webmaster@example.com>' . "\r\n"; $headers .= 'Cc: myboss@example.com' . "\r\n"; mail($to,$subject,$message,$headers); ?> Complete PHP Mail Reference

    Math Introduction

    The math functions can handle values within the range of integer and float types.

    Installation

    The PHP math functions are part of the PHP core. No installation is required to use these functions.

    Math Functions

    FunctionDescription
    abs()Returns the absolute (positive) value of a number
    acos()Returns the arc cosine of a number
    acosh()Returns the inverse hyperbolic cosine of a number
    asin()Returns the arc sine of a number
    asinh()Returns the inverse hyperbolic sine of a number
    atan()Returns the arc tangent of a number in radians
    atan2()Returns the arc tangent of two variables x and y
    atanh()Returns the inverse hyperbolic tangent of a number
    base_convert()Converts a number from one number base to another
    bindec()Converts a binary number to a decimal number
    ceil()Rounds a number up to the nearest integer
    cos()Returns the cosine of a number
    cosh()Returns the hyperbolic cosine of a number
    decbin()Converts a decimal number to a binary number
    dechex()Converts a decimal number to a hexadecimal number
    decoct()Converts a decimal number to an octal number
    deg2rad()Converts a degree value to a radian value
    exp()Calculates the exponent of e
    expm1()Returns exp(x) - 1
    floor()Rounds a number down to the nearest integer
    fmod()Returns the remainder of x/y
    getrandmax()Returns the largest possible value returned by rand()
    hexdec()Converts a hexadecimal number to a decimal number
    hypot()Calculates the hypotenuse of a right-angle triangle
    intdiv()Performs integer division
    is_finite()Checks whether a value is finite or not
    is_infinite()Checks whether a value is infinite or not
    is_nan()Checks whether a value is 'not-a-number'
    lcg_value()Returns a pseudo random number in a range between 0 and 1
    log()Returns the natural logarithm of a number
    log10()Returns the base-10 logarithm of a number
    log1p()Returns log(1+number)
    max()Returns the highest value in an array, or the highest value of several specified values
    min()Returns the lowest value in an array, or the lowest value of several specified values
    mt_getrandmax()Returns the largest possible value returned by mt_rand()
    mt_rand()Generates a random integer using Mersenne Twister algorithm
    mt_srand()Seeds the Mersenne Twister random number generator
    octdec()Converts an octal number to a decimal number
    pi()Returns the value of PI
    pow()Returns x raised to the power of y
    rad2deg()Converts a radian value to a degree value
    rand()Generates a random integer
    round()Rounds a floating-point number
    sin()Returns the sine of a number
    sinh()Returns the hyperbolic sine of a number
    sqrt()Returns the square root of a number
    srand()Seeds the random number generator
    tan()Returns the tangent of a number
    tanh()Returns the hyperbolic tangent of a number

    Predefined Math Constants

    ConstantValueDescription
    INFINFThe infinite
    M_E2.7182818284590452354Returns e
    M_EULER0.57721566490153286061Returns Euler constant
    M_LNPI1.14472988584940017414Returns the natural logarithm of PI: log_e(pi)
    M_LN20.69314718055994530942Returns the natural logarithm of 2: log_e 2
    M_LN102.30258509299404568402Returns the natural logarithm of 10: log_e 10
    M_LOG2E1.4426950408889634074Returns the base-2 logarithm of E: log_2 e
    M_LOG10E0.43429448190325182765Returns the base-10 logarithm of E: log_10 e
    M_PI3.14159265358979323846Returns Pi
    M_PI_21.57079632679489661923Returns Pi/2
    M_PI_40.78539816339744830962Returns Pi/4
    M_1_PI0.31830988618379067154Returns 1/Pi
    M_2_PI0.63661977236758134308Returns 2/Pi
    M_SQRTPI1.77245385090551602729Returns the square root of PI: sqrt(pi)
    M_2_SQRTPI1.12837916709551257390Returns 2/square root of PI: 2/sqrt(pi)
    M_SQRT1_20.70710678118654752440Returns the square root of 1/2: 1/sqrt(2)
    M_SQRT21.41421356237309504880Returns the square root of 2: sqrt(2)
    M_SQRT31.73205080756887729352Returns the square root of 3: sqrt(3)
    NANNANNot A Number
    PHP_ROUND_HALF_UP1Round halves up
    PHP_ROUND_HALF_DOWN2Round halves down
    PHP_ROUND_HALF_EVEN3Round halves to even numbers
    PHP_ROUND_HALF_ODD4Round halves to odd numbers
    PHP Math Reference

    Example

    Return the absolute value of different numbers: <?php echo(abs(6.7) . "<br>");echo(abs(-6.7) . "<br>"); echo(abs(-3) . "<br>"); echo(abs(3)); ?> Try it Yourself »

    Definition and Usage

    The abs() function returns the absolute (positive) value of a number.

    Syntax

    abs(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number. If the number is of type float, the return type is also float, otherwise it is integer

    Technical Details

    Return Value: The absolute value of the number
    Return Type: Float / Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the arc cosine of different numbers: <?php echo(acos(0.64) . "<br>");echo(acos(-0.4) . "<br>"); echo(acos(0) . "<br>"); echo(acos(-1) . "<br>"); echo(acos(1) . "<br>"); echo(acos(2)); ?> Try it Yourself »

    Definition and Usage

    The acos() function returns the arc cosine of a number. Tip: acos(-1) returns the value of Pi.

    Syntax

    acos(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number in range -1 to 1

    Technical Details

    Return Value: The arc cosine of a number. Returns NAN if number is not in the range -1 to 1
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the inverse hyperbolic cosine of different numbers: <?php echo(acosh(7) . "<br>");echo(acosh(56) . "<br>"); echo(acosh(2.45)); ?> Try it Yourself »

    Definition and Usage

    The acosh() function returns the inverse hyperbolic cosine of a number.

    Syntax

    acosh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The inverse hyperbolik cosine of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Changelog: PHP 5.3 - acosh() is now available on all platforms
    PHP Math Reference PHP Math Reference

    Example

    Return the arc sine of different numbers: <?php echo(asin(0.64) . "<br>");echo(asin(-0.4) . "<br>"); echo(asin(0) . "<br>"); echo(asin(-1) . "<br>"); echo(asin(1) . "<br>"); echo(asin(2)); ?> Try it Yourself »

    Definition and Usage

    The asin() function returns the arc sine of a number. Tip: asin(1) returns the value of Pi/2.

    Syntax

    asin(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number in range -1 to 1

    Technical Details

    Return Value: The arc sine of a number. Returns NAN if number is not in the range -1 to 1
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the inverse hyperbolic sine of different numbers: <?php echo(asinh(7) . "<br>");echo(asinh(56) . "<br>"); echo(asinh(2.45)); ?> Try it Yourself »

    Definition and Usage

    The asinh() function returns the inverse hyperbolic sine of a number.

    Syntax

    asinh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The inverse hyperbolic sine of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Changelog: PHP 5.3 - asinh() is now available on all platforms
    PHP Math Reference PHP Math Reference

    Example

    Return the arc tangent of different numbers with the atan() function: <?php echo(atan(0.50) . "<br>"); echo(atan(-0.50) . "<br>"); echo(atan(5) . "<br>"); echo(atan(-5) . "<br>"); echo(atan(100) . "<br>"); echo(atan(-100)); ?> Try it Yourself »

    Definition and Usage

    The atan() function returns the arc tangent of arg as a numeric value between -Pi/2 and Pi/2 radians.

    Syntax

    atan(arg);

    Parameter Values

    ParameterDescription
    argRequired. Specifies an argument to process

    Technical Details

    Return Value: The arc tangent of arg in radians
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the arc tangent of two variables with the atan2() function: <?php echo(atan2(0.50,0.50) . "<br>"); echo(atan2(-0.50,-0.50) . "<br>"); echo(atan2(5,5) . "<br>"); echo(atan2(10,20) . "<br>"); echo(atan2(-5,-5) . "<br>"); echo(atan2(-10,10)); ?> Try it Yourself »

    Definition and Usage

    The atan2() function returns the arc tangent of two variables x and y.

    Syntax

    atan2(y,x);

    Parameter Values

    ParameterDescription
    yRequired. Specifies the dividend
    xRequired. Specifies the divisor

    Technical Details

    Return Value: The arc tangent of y/x in radians, which is between -Pi and Pi
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the inverse hyperbolic tangent of different numbers: <?php echo(atanh(M_PI_4) . "<br>");echo(atanh(0.50) . "<br>"); echo(atanh(-0.50) . "<br>");echo(atanh(1) . "<br>");echo(atanh(-1)); ?> Try it Yourself »

    Definition and Usage

    The atanh() function returns the inverse hyperbolic tangent of a number.

    Syntax

    atanh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The hyperbolic tangent of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Changelog: PHP 5.3 - atanh() is now available on all platforms
    PHP Math Reference PHP Math Reference

    Example

    Convert a hexadecimal number to octal number: <?php $hex = "E196"; echo base_convert($hex,16,8); ?> Try it Yourself »

    Definition and Usage

    The base_convert() function converts a number from one number base to another.

    Syntax

    base_convert(number,frombase,tobase);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the number to convert
    frombaseRequired. Specifies the original base of number. Has to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35
    tobaseRequired. Specifies the base to convert to. Has to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35

    Technical Details

    Return Value: The number converted to the specified base
    Return Type: String
    PHP Version: 4+

    More Examples

    Example

    Convert an octal number to a decimal number: <?php $oct = "0031"; echo base_convert($oct,8,10); ?> Try it Yourself »

    Example

    Convert an octal number to a hexadecimal number: <?php $oct = "364"; echo base_convert($oct,8,16); ?> Try it Yourself » PHP Math Reference PHP Math Reference

    Example

    Convert binary to decimal: <?php echo bindec("0011") . "<br>"; echo bindec("01") . "<br>"; echo bindec("11000110011") . "<br>"; echo bindec("111"); ?> Try it Yourself »

    Definition and Usage

    The bindec() function converts a binary number to a decimal number. Tip: To convert decimal to binary, look at the decbin() function.

    Syntax

    bindec(binary_string);

    Parameter Values

    ParameterDescription
    binary_stringRequired. Specifies the binary string to convert.Note: Must be a string!

    Technical Details

    Return Value: The decimal value of binary_string
    Return Type: Float / Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Round numbers up to the nearest integer: <?php echo(ceil(0.60) . "<br>"); echo(ceil(0.40) . "<br>"); echo(ceil(5) . "<br>"); echo(ceil(5.1) . "<br>"); echo(ceil(-5.1) . "<br>"); echo(ceil(-5.9)); ?> Try it Yourself »

    Definition and Usage

    The ceil() function rounds a number UP to the nearest integer, if necessary. Tip: To round a number DOWN to the nearest integer, look at the floor() function. Tip: To round a floating-point number, look at the round() function.

    Syntax

    ceil(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the value to round up

    Technical Details

    Return Value: The value rounded up to the nearest integer
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the cosine of different numbers: <?php echo(cos(3) . "<br>"); echo(cos(-3) . "<br>"); echo(cos(0) . "<br>"); echo(cos(M_PI) . "<br>"); echo(cos(2*M_PI)); ?> Try it Yourself »

    Definition and Usage

    The cos() function returns the cosine of a number. Note: The cos() function returns a numeric value between -1 and 1, which represents the cosine of the angle.

    Syntax

    cos(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The cosine of number
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the hyperbolic cosine of different numbers: <?php echo(cosh(3) . "<br>"); echo(cosh(-3) . "<br>"); echo(cosh(0) . "<br>"); echo(cosh(M_PI) . "<br>"); echo(cosh(2*M_PI)); ?> Try it Yourself »

    Definition and Usage

    The cosh() function returns the hyperbolic cosine of a number (equivalent to (exp(number) + exp(-number)) / 2).

    Syntax

    cosh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The hyperbolic cosine of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Math Reference PHP Math Reference

    Example

    Convert decimal to binary: <?php echo decbin("3") . "<br>"; echo decbin("1") . "<br>"; echo decbin("1587") . "<br>"; echo decbin("7"); ?> Try it Yourself »

    Definition and Usage

    The decbin() function converts a decimal number to a binary number. Tip: To convert binary to decimal, look at the bindec() function.

    Syntax

    decbin(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the decimal value to convert

    Technical Details

    Return Value: A string that contains the binary number of the decimal value
    Return Type: String
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Convert decimal to hexadecimal: <?php echo dechex("30") . "<br>"; echo dechex("10") . "<br>"; echo dechex("1587") . "<br>"; echo dechex("70"); ?> Try it Yourself »

    Definition and Usage

    The dechex() function converts a decimal number to a hexadecimal number. Tip: To convert hexadecimal to decimal, look at the hexdec() function.

    Syntax

    dechex(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the decimal value to convert

    Technical Details

    Return Value: A string that contains the hexadecimal number of the decimal value
    Return Type: String
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Convert decimal to octal: <?php echo decoct("30") . "<br>"; echo decoct("10") . "<br>"; echo decoct("1587") . "<br>"; echo decoct("70"); ?> Try it Yourself »

    Definition and Usage

    The decoct() function converts a decimal number to an octal number. Tip: To convert octal to decimal, look at the octdec() function.

    Syntax

    decoct(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the decimal value to convert

    Technical Details

    Return Value: A string that contains the octal number of the decimal value
    Return Type: String
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Convert degrees to radians: <?php echo deg2rad("45") . "<br>"; echo deg2rad("90") . "<br>"; echo deg2rad("360"); ?> Try it Yourself »

    Definition and Usage

    The deg2rad() function converts a degree value to a radian value. Tip: To convert a radian value to a degree value, look at the rad2deg() function.

    Syntax

    deg2rad(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the degree to convert

    Technical Details

    Return Value: The radian equivalent of number
    Return Type: Float
    PHP Version: 4+

    More Examples

    Example

    Convert a degree into its radian equivalent: <?php $deg = 180; $rad = deg2rad($deg); echo "$deg degrees is equal to $rad radians."; ?> Try it Yourself » PHP Math Reference PHP Math Reference

    Example

    Return 'e' raised to the power of different numbers: <?php echo(exp(0) . "<br>");echo(exp(1) . "<br>"); echo(exp(10) . "<br>"); echo(exp(4.8)); ?> Try it Yourself »

    Definition and Usage

    The exp() function returns e raised to the power of x (ex). 'e' is the base of the natural system of logarithms (approximately 2.718282) and x is the number passed to it.

    Syntax

    exp(x);

    Parameter Values

    ParameterDescription
    xRequired. Specifies the exponent

    Technical Details

    Return Value: 'e' raised to the power of x
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return exp() - 1: <?php echo(expm1(0) . "<br>");echo(expm1(1) . "<br>"); echo(expm1(10) . "<br>"); echo(expm1(4.8)); ?> Try it Yourself »

    Definition and Usage

    The expm1() function returns exp(x) - 1.

    Syntax

    expm1(x);

    Parameter Values

    ParameterDescription
    xRequired. Specifies the exponent

    Technical Details

    Return Value: 'e' raised to the power of x minus 1
    Return Type: Float
    PHP Version: 4.1+
    PHP Changelog: PHP 5.3 - expm1() is now available on all platforms
    PHP Math Reference PHP Math Reference

    Example

    Round numbers down to the nearest integer: <?php echo(floor(0.60) . "<br>"); echo(floor(0.40) . "<br>"); echo(floor(5) . "<br>"); echo(floor(5.1) . "<br>"); echo(floor(-5.1) . "<br>"); echo(floor(-5.9)); ?> Try it Yourself »

    Definition and Usage

    The floor() function rounds a number DOWN to the nearest integer, if necessary. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a floating-point number, look at the round() function.

    Syntax

    floor(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the value to round down

    Technical Details

    Return Value: The value rounded down to the nearest integer
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the remainder of x/y: <?php $x = 7;$y = 2;$result = fmod($x,$y); echo $result;// $result equals 1, because 2 * 3 + 1 = 7 ?> Try it Yourself »

    Definition and Usage

    The fmod() function returns the remainder (modulo) of x/y.

    Syntax

    fmod(x,y);

    Parameter Values

    ParameterDescription
    xRequired. Specifies the dividend
    yRequired. Specifies the divisor

    Technical Details

    Return Value: The floating point remainder of x/y
    Return Type: Float
    PHP Version: 4.2+
    PHP Math Reference PHP Math Reference

    Example

    Return largest possible random value that can be returned by rand(): <?php echo(getrandmax()); ?> Try it Yourself »

    Definition and Usage

    The getrandmax() function returns the largest possible value that can be returned by rand().

    Syntax

    getrandmax();

    Technical Details

    Return Value: The largest possible value returned by rand()
    Return Type: Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Convert hexadecimal to decimal: <?php echo hexdec("1e") . "<br>"; echo hexdec("a") . "<br>"; echo hexdec("11ff") . "<br>"; echo hexdec("cceeff"); ?> Try it Yourself »

    Definition and Usage

    The hexdec() function converts a hexadecimal number to a decimal number. Tip: To convert decimal to hexadecimal, look at the dechex() function.

    Syntax

    hexdec(hex_string);

    Parameter Values

    ParameterDescription
    hex_stringRequired. Specifies the hexadecimal string to convert

    Technical Details

    Return Value: The decimal value of hex_string
    Return Type: Float / Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Calculate the hypotenuse of different right-angle triangles: <?php echo hypot(3,4) . "<br>"; echo hypot(4,6) . "<br>"; echo hypot(1,3) . "<br>";echo sqrt(3*3+4*4); ?> Try it Yourself »

    Definition and Usage

    The hypot() function calculates the hypotenuse of a right-angle triangle. Tip: This function is equivalent to sqrt(x*x + y*y).

    Syntax

    hypot(x,y);

    Parameter Values

    ParameterDescription
    xRequired. Specifies the length of first side
    yRequired. Specifies the length of second side

    Technical Details

    Return Value: The length of the hypotenuse
    Return Type: Float
    PHP Version: 4.1+
    PHP Math Reference PHP Math Reference

    Example

    Perform some integer divisions: <?php echo intdiv(8, 4) . "<br>"; echo intdiv(5, 2) . "<br>"; echo intdiv(-5, -2); ?> Try it Yourself »

    Definition and Usage

    The intdiv() function is used for integer division.

    Syntax

    intdiv(dividend, divisor);

    Parameter Values

    ParameterDescription
    dividendRequired. Specifies a number that will be divided
    divisorRequired. Specifies the number to divide the dividend by

    Technical Details

    Return Value: The integer part of the division
    Return Type: Integer
    PHP Version: 7+
    PHP Math Reference PHP Math Reference

    Example

    Check whether a value is finite or not: <?php echo is_finite(2) . "<br>"; echo is_finite(log(0)) . "<br>"; echo is_finite(2000); ?> Try it Yourself »

    Definition and Usage

    The is_finite() function checks whether a value is finite or not. This function returns true (1) if the specified value is a finite number, otherwise it returns false/nothing. The value is finite if it is within the allowed range for a PHP float on this platform.

    Syntax

    is_finite(value);

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to check

    Technical Details

    Return Value: TRUE if value is a finite number, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.2+
    PHP Math Reference PHP Math Reference

    Example

    Check whether a value is infinite or not: <?php echo is_infinite(2) . "<br>"; echo is_infinite(log(0)) . "<br>"; echo is_infinite(2000); ?> Try it Yourself »

    Definition and Usage

    The is_infinite() function checks whether a value is infinite or not. This function returns true (1) if the specified value is an infinite number, otherwise it returns false/nothing. The value is infinite if it is outside the allowed range for a PHP float on this platform.

    Syntax

    is_infinite(value);

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to check

    Technical Details

    Return Value: TRUE if value is an infinite number, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.2+
    PHP Math Reference PHP Math Reference

    Example

    Check whether a value is 'not-a-number': <?php echo is_nan(200) . "<br>";echo is_nan(acos(1.01)); ?> Try it Yourself »

    Definition and Usage

    The is_nan() function checks whether a value is 'not a number'. This function returns true (1) if the specified value is 'not-a-number', otherwise it returns false/nothing.

    Syntax

    is_nan(value);

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to check

    Technical Details

    Return Value: TRUE if value is 'not a number', FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.2+
    PHP Math Reference PHP Math Reference

    Example

    Return a pseudo random number in a range between 0 and 1: <?php echo lcg_value();?> Try it Yourself »

    Definition and Usage

    The lcg_value() function returns a pseudo random number in a range between 0 and 1.

    Syntax

    lcg_value();

    Technical Details

    Return Value: A pseudo random float value in a range between 0 and 1
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the natural logarithm of different numbers: <?php echo(log(2.7183) . "<br>"); echo(log(2) . "<br>"); echo(log(1) . "<br>"); echo(log(0); ?> Try it Yourself »

    Definition and Usage

    The log() function returns the natural logarithm of a number, or the logarithm of number to base.

    Syntax

    log(number,base);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the value to calculate the logarithm for
    baseOptional. The logarithmic base to use. Default is 'e'

    Technical Details

    Return Value: The natural logarithm of a number, or the logarithm of number to base
    Return Type: Float
    PHP Version: 4+
    PHP Changelog: PHP 4.3: The base parameter were added
    PHP Math Reference PHP Math Reference

    Example

    Return the base-10 logarithm of different numbers: <?php echo(log10(2.7183) . "<br>"); echo(log10(2) . "<br>"); echo(log10(1) . "<br>"); echo(log10(0)); ?> Try it Yourself »

    Definition and Usage

    The log10() function returns the base-10 logarithm of a number.

    Syntax

    log10(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the value to calculate the logarithm for

    Technical Details

    Return Value: The base-10 logarithm of number
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return log(1+number) for different numbers: <?php echo(log1p(2.7183) . "<br>"); echo(log1p(2) . "<br>"); echo(log1p(1) . "<br>"); echo(log1p(0)); ?> Try it Yourself »

    Definition and Usage

    The log1p() function returns log(1+number), computed in a way that is accurate even when the value of number is close to zero.

    Syntax

    log1p(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the number to process

    Technical Details

    Return Value: log(1+number)
    Return Type: Float
    PHP Version: 4.1+
    PHP Changelog: PHP 5.3: The log1p() function is now available on all platforms
    PHP Math Reference PHP Math Reference

    Example

    Find highest value with the max() function: <?php echo(max(2,4,6,8,10) . "<br>");echo(max(22,14,68,18,15) . "<br>"); echo(max(array(4,6,8,10)) . "<br>");echo(max(array(44,16,81,12)));?> Try it Yourself »

    Definition and Usage

    The max() function returns the highest value in an array, or the highest value of several specified values.

    Syntax

    max(array_values);ormax(value1,value2,...);

    Parameter Values

    ParameterDescription
    array_valuesRequired. Specifies an array containing the values
    value1,value2,...Required. Specifies the values to compare (must be at least two values)

    Technical Details

    Return Value: The numerically highest value
    Return Type: Mixed
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Find lowest value with the min() function: <?php echo(min(2,4,6,8,10) . "<br>");echo(min(22,14,68,18,15) . "<br>"); echo(min(array(4,6,8,10)) . "<br>");echo(min(array(44,16,81,12)));?> Try it Yourself »

    Definition and Usage

    The min() function returns the lowest value in an array, or the lowest value of several specified values.

    Syntax

    min(array_values);ormin(value1,value2,...);

    Parameter Values

    ParameterDescription
    array_valuesRequired. Specifies an array containing the values
    value1,value2,...Required. Specifies the values to compare (must be at least two values)

    Technical Details

    Return Value: The numerically lowest value
    Return Type: Mixed
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return largest possible random value that can be returned by mt_rand(): <?php echo(mt_getrandmax()); ?> Try it Yourself »

    Definition and Usage

    The mt_getrandmax() function returns the largest possible value that can be returned by mt_rand().

    Syntax

    mt_getrandmax();

    Technical Details

    Return Value: The largest possible value returned by mt_rand()
    Return Type: Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Generate random numbers: <?php echo(mt_rand() . "<br>"); echo(mt_rand() . "<br>"); echo(mt_rand(10,100));?> Try it Yourself »

    Definition and Usage

    The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Tip: This function produces a better random value, and is 4 times faster than rand(). Tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).

    Syntax

    mt_rand();ormt_rand(min,max);

    Parameter Values

    ParameterDescription
    minOptional. Specifies the lowest number to be returned. Default is 0
    maxOptional. Specifies the highest number to be returned. Default is mt_getrandmax()

    Technical Details

    Return Value: A random integer between min (or 0) and max (or mt_getrandmax() inclusive). Returns FALSE if max < min
    Return Type: Integer
    PHP Version: 4+
    PHP Changelog: PHP 7.1: rand() has been an alias of mt_rand()PHP 5.3.4: Issues an E_WARNING and returns FALSE if max < min.PHP 4.2.0: Random number generator is seeded automatically.
    PHP Math Reference PHP Math Reference

    Example

    Seed the random number generator: <?php mt_srand(mktime()); echo(mt_rand());?> Try it Yourself »

    Definition and Usage

    The mt_srand() function seeds the Mersenne Twister random number generator.

    Syntax

    mt_srand(seed, mode);

    Parameter Values

    ParameterDescription
    seedOptional. Specifies the seed value
    modeOptional. Specifies the algorithm to use. Can be one of the following constants:
  • MT_RAND_MT19937 - uses the fixed, correct Mersenne Twister implementation (which is used from PHP 7.1)
  • MT_RAND_PHP - uses the incorrect Mersenne Twister implementation (which was used up to PHP 7.1)
  • Technical Details

    Return Value: None
    Return Type: -
    PHP Version: 4+
    PHP Changelog: PHP 4.2.0: Random number generator is now seeded automatically
    PHP Math Reference PHP Math Reference

    Example

    Convert octal to decimal: <?php echo octdec("36") . "<br>"; echo octdec("12") . "<br>"; echo octdec("3063") . "<br>"; echo octdec("106"); ?> Try it Yourself »

    Definition and Usage

    The octdec() function converts an octal number to a decimal number. Tip: To convert decimal to octal, look at the decoct() function.

    Syntax

    octdec(octal_string);

    Parameter Values

    ParameterDescription
    octal_stringRequired. Specifies the octal string to convert

    Technical Details

    Return Value: The decimal value of octal_string
    Return Type: Float / Integer
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the value of PI: <?php echo(pi());?> Try it Yourself »

    Definition and Usage

    The pi() function returns the value of PI. Tip: The named constant M_PI is identical to pi().

    Syntax

    pi();

    Technical Details

    Return Value: 3.1415926535898
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Examples of pow(): <?php echo(pow(2,4) . "<br>");echo(pow(-2,4) . "<br>");echo(pow(-2,-4) . "<br>");echo(pow(-2,-3.2));?> Try it Yourself »

    Definition and Usage

    The pow() function returns x raised to the power of y.

    Syntax

    pow(x,y);

    Parameter Values

    ParameterDescription
    xRequired. Specifies the base to use
    yRequired. Specifies the exponent

    Technical Details

    Return Value: x raised to the power of y
    Return Type: Integer if possible, Float otherwise
    PHP Version: 4+
    PHP Changelog: PHP 4.0.6: Will now return integer if possible. Earlier it only returned floatPHP 4.2.0: No warning is issued on errors
    PHP Math Reference PHP Math Reference

    Example

    Convert radians to degrees: <?php echo rad2deg(pi()) . "<br>"; echo rad2deg(pi()/4); ?> Try it Yourself »

    Definition and Usage

    The rad2deg() function converts a radian value to a degree value. Tip: To convert a degree value to a radian value, look at the deg2rad() function.

    Syntax

    rad2deg(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a radian value to convert

    Technical Details

    Return Value: The equivalent of number in degrees
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Generate random numbers: <?php echo(rand() . "<br>"); echo(rand() . "<br>"); echo(rand(10,100));?> Try it Yourself »

    Definition and Usage

    The rand() function generates a random integer. Tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: The mt_rand() function produces a better random value, and is 4 times faster than rand().

    Syntax

    rand();orrand(min,max);

    Parameter Values

    ParameterDescription
    minOptional. Specifies the lowest number to be returned. Default is 0
    maxOptional. Specifies the highest number to be returned. Default is getrandmax()

    Technical Details

    Return Value: A random integer between min (or 0) and max (or getrandmax() inclusive)
    Return Type: Integer
    PHP Version: 4+
    PHP Changelog: PHP 7.1: The rand() function is an alias of mt_rand().PHP 4.2.0: The random number generator is seeded automatically.
    PHP Math Reference PHP Math Reference

    Example

    Round numbers: <?php echo(round(0.60) . "<br>"); echo(round(0.50) . "<br>"); echo(round(0.49) . "<br>"); echo(round(-4.40) . "<br>"); echo(round(-4.60)); ?> Try it Yourself »

    Definition and Usage

    The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.

    Syntax

    round(number,precision,mode);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies the value to round
    precisionOptional. Specifies the number of decimal digits to round to. Default is 0
    modeOptional. Specifies a constant to specify the rounding mode:
  • PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2
  • PHP_ROUND_HALF_DOWN - Round number down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1
  • PHP_ROUND_HALF_EVEN - Round number to precision decimal places towards the next even value
  • PHP_ROUND_HALF_ODD - Round number to precision decimal places towards the next odd value
  • Technical Details

    Return Value: The rounded value
    Return Type: Float
    PHP Version: 4+
    PHP Changelog: PHP 5.3: The mode parameter was added

    More Examples

    Example

    Round numbers to two decimals: <?php echo(round(4.96754,2) . "<br>");echo(round(7.045,2) . "<br>"); echo(round(7.055,2)); ?> Try it Yourself »

    Example

    Round numbers using the constants: <?php echo(round(1.5,0,PHP_ROUND_HALF_UP) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_DOWN) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_DOWN) . "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "<br>"); echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "<br>"); echo(round(-1.5,0,PHP_ROUND_HALF_ODD)); ?> Try it Yourself » PHP Math Reference PHP Math Reference

    Example

    Return the sine of different numbers: <?php echo(sin(3) . "<br>"); echo(sin(-3) . "<br>"); echo(sin(0) . "<br>"); echo(sin(M_PI) . "<br>"); echo(sin(M_PI_2)); ?> Try it Yourself »

    Definition and Usage

    The sin() function returns the sine of a number.

    Syntax

    sin(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a value in radians

    Technical Details

    Return Value: The sine of number
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the hyperbolic sine of different numbers: <?php echo(sinh(3) . "<br>"); echo(sinh(-3) . "<br>"); echo(sinh(0) . "<br>"); echo(sinh(M_PI) . "<br>"); echo(sinh(M_PI_2)); ?> Try it Yourself »

    Definition and Usage

    The sinh() function returns the hyperbolic sine of a number, which is equal to (exp(number) - exp(-number))/2).

    Syntax

    sinh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The hyperbolic sine of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Math Reference PHP Math Reference

    Example

    Return the square root of different numbers: <?php echo(sqrt(0) . "<br>"); echo(sqrt(1) . "<br>"); echo(sqrt(9) . "<br>"); echo(sqrt(0.64) . "<br>"); echo(sqrt(-9)); ?> Try it Yourself »

    Definition and Usage

    The sqrt() function returns the square root of a number.

    Syntax

    sqrt(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The square root of number, or NAN for negative numbers
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Seed the random number generator: <?php srand(mktime()); echo(rand());?> Try it Yourself »

    Definition and Usage

    The srand() function seeds the random number generator (rand()). Tip: From PHP 4.2.0, the random number generator is seeded automatically and there is no need to use this function.

    Syntax

    srand(seed);

    Parameter Values

    ParameterDescription
    seedOptional. Specifies the seed value

    Technical Details

    Return Value: None
    Return Type: -
    PHP Version: 4+
    PHP Changelog: PHP 7.1.0: srand() has been an alias of mt_srand().PHP 4.2.0: Random number generator is now seeded automatically.
    PHP Math Reference PHP Math Reference

    Example

    Return the tangent of different numbers: <?php echo(tan(M_PI_4) . "<br>"); echo(tan(0.50) . "<br>"); echo(tan(-0.50) . "<br>"); echo(tan(5) . "<br>"); echo(tan(10) . "<br>"); echo(tan(-5) . "<br>"); echo(tan(-10)); ?> Try it Yourself »

    Definition and Usage

    The tan() function returns the tangent of a number.

    Syntax

    tan(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a value in radians

    Technical Details

    Return Value: The tangent of number
    Return Type: Float
    PHP Version: 4+
    PHP Math Reference PHP Math Reference

    Example

    Return the hyperbolic tangent of different numbers: <?php echo(tanh(M_PI_4) . "<br>"); echo(tanh(0.50) . "<br>"); echo(tanh(-0.50) . "<br>"); echo(tanh(5) . "<br>"); echo(tanh(10) . "<br>"); echo(tanh(-5) . "<br>"); echo(tanh(-10)); ?> Try it Yourself »

    Definition and Usage

    The tanh() function returns the hyperbolic tangent of a number, which is equal to sinh(x)/cosh(x).

    Syntax

    tanh(number);

    Parameter Values

    ParameterDescription
    numberRequired. Specifies a number

    Technical Details

    Return Value: The hyperbolic tangent of number
    Return Type: Float
    PHP Version: 4.1+
    PHP Math Reference

    Miscellaneous Introduction

    The misc. functions were only placed here because none of the other categories seemed to fit.

    Installation

    The misc. functions are part of the PHP core. No installation is required to use these functions.

    Runtime Configuration

    The behavior of the misc. functions is affected by settings in the php.ini file. Misc. configuration options:
    NameDescriptionDefaultChangeable
    ignore_user_abortFALSE indicates that scripts will be terminated as soon as they try to output something after a client has aborted their connection"0"PHP_INI_ALL
    highlight.stringColor for highlighting a string in PHP syntax"#DD0000" PHP_INI_ALL
    highlight.commentColor for highlighting PHP comments"#FF8000"PHP_INI_ALL
    highlight.keyword Color for syntax highlighting PHP keywords (e.g. parenthesis and semicolon) "#007700"PHP_INI_ALL
    highlight.default Default color for PHP syntax"#0000BB"PHP_INI_ALL
    highlight.htmlColor for HTML code"#000000" PHP_INI_ALL
    browscapName and location of browser-capabilities file (e.g. browscap.ini) NULLPHP_INI_SYSTEM

    Miscellaneous Functions

    FunctionDescription
    connection_aborted()Checks whether the client has disconnected
    connection_status()Returns the current connection status
    connection_timeout()Deprecated from PHP 4.0.5. Checks whether the script has timed out
    constant()Returns the value of a constant
    define()Defines a constant
    defined()Checks whether a constant exists
    die()Alias of exit()
    eval()Evaluates a string as PHP code
    exit()Prints a message and exits the current script
    get_browser()Returns the capabilities of the user's browser
    __halt_compiler()Halts the compiler execution
    highlight_file()Outputs a file with the PHP syntax highlighted
    highlight_string()Outputs a string with the PHP syntax highlighted
    hrtime()Returns the system's high resolution time
    ignore_user_abort()Sets whether a remote client can abort the running of a script
    pack()Packs data into a binary string
    php_strip_whitespace()Returns the source code of a file with PHP comments and whitespace removed
    show_source()Alias of highlight_file()
    sleep()Delays code execution for a number of seconds
    sys_getloadavg()Returns the system load average
    time_nanosleep()Delays code execution for a number of seconds and nanoseconds
    time_sleep_until()Makes a script sleep until the specified time
    uniqid()Generates a unique ID
    unpack()Unpacks data from a binary string
    usleep()Delays code execution for a number of microseconds

    Predefined Misc. Constants

    ConstantDescription
    CONNECTION_ABORTEDConnection is aborted by user or network error
    CONNECTION_NORMALConnection is running normally
    CONNECTION_TIMEOUTConnection timed out
    __COMPILER_HALT_OFFSET__
    PHP Misc Reference

    Example

    Create a function (check_abort()) that writes a log message if a client aborts the script: <?phpfunction check_abort() { if (connection_aborted()) error_log ("Script $GLOBALS[SCRIPT_NAME]" . "$GLOBALS[SERVER_NAME] was aborted by the user."); } // Some script to be executed here // Call the check_abort function when the script ends register_shutdown_function("check_abort"); ?>

    Definition and Usage

    The connection_aborted() function checks whether the client has disconnected.

    Syntax

    connection_aborted()

    Technical Details

    Return Value: Returns 1 if the connection has been aborted, otherwise it returns 0
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Return the connection satus: <?phpswitch (connection_status()) { case CONNECTION_NORMAL: $txt = 'Connection is in a normal state'; break; case CONNECTION_ABORTED: $txt = 'Connection aborted'; break; case CONNECTION_TIMEOUT: $txt = 'Connection timed out'; break; case (CONNECTION_ABORTED & CONNECTION_TIMEOUT): $txt = 'Connection aborted and timed out'; break; default: $txt = 'Unknown'; break; } echo $txt; ?> Try it Yourself »

    Definition and Usage

    The connection_status() function returns the current connection status. Possible values that can be returned are:
  • 0 - CONNECTION_NORMAL - connection is running normally
  • 1 - CONNECTION_ABORTED - connection is aborted by user or network error
  • 2 - CONNECTION_TIMEOUT - connection timed out
  • 3 - CONNECTION_ABORTED & CONNECTION_TIMEOUT
  • Syntax

    connection_status()

    Technical Details

    Return Value: Returns the connection status bitfield
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Definition and Usage

    The connection_timeout() function was deprecated and removed in PHP version 4.0.5. The connection_timeout() function checks whether the script has timed out.

    Syntax

    connection_timeout()

    Technical Details

    Return Value: Returns 1 if the script has timed out, otherwise it returns 0
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Return the value of a constant: <?php//define a constant define("GREETING","Hello you! How are you today?"); echo constant("GREETING"); ?> Try it Yourself »

    Definition and Usage

    The constant() function returns the value of a constant. Note: This function also works with class constants.

    Syntax

    constant(constant)

    Parameter Values

    ParameterDescription
    constantRequired. Specifies the name of the constant to check

    Technical Details

    Return Value: Returns the value of a constant, or NULL if the constant is not defined
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Define a case-sensitive constant: <?phpdefine("GREETING","Hello you! How are you today?"); echo constant("GREETING"); ?> Try it Yourself »

    Definition and Usage

    The define() function defines a constant. Constants are much like variables, except for the following differences:
  • A constant's value cannot be changed after it is set
  • Constant names do not need a leading dollar sign ($)
  • Constants can be accessed regardless of scope
  • Constant values can only be strings and numbers
  • Syntax

    define(name,value,case_insensitive)

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the constant
    valueRequired. Specifies the value of the constant.
    case_insensitiveOptional. Specifies whether the constant name should be case-insensitive. Possible values:
  • TRUE - Case-insensitive (deprecated in PHP 7.3)
  • FALSE - Case-sensitive (this is default)
  • Technical Details

    Return Value: Returns TRUE on success or FALSE on failure
    PHP Version: 4+
    Changelog: PHP 7.3: Defining case-insensitive constants is deprecated.PHP 7: The value parameter can also be an array.PHP 5: The value parameter must be a string, integer, float, boolean or NULL.
    PHP Misc Reference PHP Misc Reference

    Example

    Check if a constant exists: <?phpdefine("GREETING","Hello you! How are you today?"); echo defined("GREETING"); ?> Try it Yourself »

    Definition and Usage

    The defined() function checks whether a constant exists.

    Syntax

    defined(name)

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the constant to check

    Technical Details

    Return Value: Returns TRUE if the constant exists, or FALSE otherwise
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Print a message and terminate the current script: <?php$site = "https://www.w3schools.com/"; fopen($site,"r") or die("Unable to connect to $site"); ?>

    Definition and Usage

    The die() function is an alias of the exit() function.

    Syntax

    die(message)

    Parameter Values

    ParameterDescription
    messageRequired. A message or status number to print before terminating the script. A status number will not be written to the output, just used as the exit status.

    Technical Details

    Return Value: Nothing
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Evaluate a string as PHP code: <?php$string = "beautiful"; $time = "winter"; $str = 'This is a $string $time morning!'; echo $str. "<br>"; eval("\$str = \"$str\";"); echo $str; ?> The output of the code above will be: This is a $string $time morning! This is a beautiful winter morning!

    Definition and Usage

    The eval() function evaluates a string as PHP code. The string must be valid PHP code and must end with semicolon. Note: A return statement will terminate the evaluation of the string immediately. Tip: This function can be useful for storing PHP code in a database.

    Syntax

    eval(phpcode)

    Parameter Values

    ParameterDescription
    phpcodeRequired. Specifies the PHP code to be evaluated

    Technical Details

    Return Value: Returns NULL unless a return statement is called in the code string. Then the value passed to return is returned. If there is a parse error in the code string, eval() returns FALSE.
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Print a message and exit the current script: <?php$site = "https://www.w3schools.com/"; fopen($site,"r") or exit("Unable to connect to $site"); ?>

    Definition and Usage

    The exit() function prints a message and terminates the current script.

    Syntax

    exit(message)

    Parameter Values

    ParameterDescription
    messageRequired. A message or status number to print before terminating the script. A status number will not be written to the output, just used as the exit status.

    Technical Details

    Return Value: Nothing
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Look up the browscap.ini file and return the capabilities of the browser: <?phpecho $_SERVER['HTTP_USER_AGENT'];$browser = get_browser(); print_r($browser); ?> Try it Yourself »

    Definition and Usage

    The get_browser() function looks up the user's browscap.ini file and returns the capabilities of the user's browser.

    Syntax

    get_browser(user_agent,return_array)

    Parameter Values

    ParameterDescription
    user_agentOptional. Specifies the name of an HTTP user agent. Default is the value of $HTTP_USER_AGENT. You can bypass this parameter with NULL
    return_arrayOptional. If this parameter is set to TRUE, the function will return an array instead of an object

    Technical Details

    Return Value: Returns an object or an array with information about the user's browser on success, or FALSE on failure
    PHP Version: 4+
    Changelog: The return_array parameter was added in PHP 4.3.2
    PHP Misc Reference PHP Misc Reference

    Definition and Usage

    The __halt_compiler() function halts the compiler execution.

    Syntax

    __halt_compiler()

    Technical Details

    Return Value: Nothing
    PHP Version: 5.1+
    PHP Misc Reference PHP Misc Reference

    Example

    Using a test file ("test.php") to output the file with the PHP syntax highlighted: <html> <body> <?php highlight_file("test.php"); ?> </body> </html> The browser output of the code above could be (depending on the content in your file): <html> <body> <?php echo ("test.php"); ?> </body></html> The HTML output of the code above could be (View Source): <html><body><code><span style="color: #000000">&lt;html&gt;<br />&lt;body&gt;<br /><span style="color: #0000BB">&lt;?php<br /></span><span style="color: #007700">echo&nbsp;(</span><span style="color: #DD0000">"test.php"</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?&gt; <br /></span>&lt;/body&gt;<br />&lt;/html&gt;</span></code></body></html> Try it Yourself »

    Definition and Usage

    The highlight_file() function outputs a file with the PHP syntax highlighted. The syntax is highlighted by using HTML tags. Tip: The colors used for syntax highlighting can be set in the php.ini file or with the ini_set() function. Note: When using this function, the entire file will be displayed - including passwords and any other sensitive information!

    Syntax

    highlight_file(filename,return)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file to be highlighted
    returnOptional. If set to TRUE, this function will return the highlighted code as a string, instead of printing it out. Default is FALSE

    Technical Details

    Return Value: If the return parameter is set to TRUE, this function returns the highlighted code as a string instead of printing it out. Otherwise, it returns TRUE on success, or FALSE on failure
    PHP Version: 4+
    Changelog: PHP 4.2.1 - This function is now also affected by safe_mode and open_basedir. However, safe_mode was deprecated and removed in PHP 5.4.PHP 4.2 - The return parameter was added.
    PHP Misc Reference PHP Misc Reference

    Example

    Output a string with the PHP syntax highlighted: <html> <body> <?php highlight_string("Hello world! <?php phpinfo(); ?>"); ?> </body> </html> The browser output of the code above will be: Hello world! <?php phpinfo(); ?> The HTML output of the code above will be (View Source): <html> <body> <code> <span style="color: #000000">Hello&nbsp;world!&nbsp; <span style="color: #0000BB">&lt;?php&nbsp;phpinfo</span> <span style="color: #007700">();&nbsp;</span> <span style="color: #0000BB">?&gt;</span> </span> </code> </body></html> Try it Yourself »

    Definition and Usage

    The highlight_string() function outputs a string with the PHP syntax highlighted. The string is highlighted by using HTML tags. The colors used for syntax highlighting can be set in the php.ini file or with the ini_set() function.

    Syntax

    highlight_string(string,return)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to be highlighted
    returnOptional. If set to TRUE, this function will return the highlighted code as a string, instead of printing it out. Default is FALSE

    Technical Details

    Return Value: Returns TRUE on success, or FALSE on failure
    PHP Version: 4+
    Changelog: The return parameter was added in PHP 4.2.0
    PHP Misc Reference PHP Misc Reference

    Example

    Return the system's high resolution time: <html> <body> <?php echo hrtime(); ?> </body> </html> The output of the code above could be something like this: 233568471904329635

    Definition and Usage

    The hrtime() function returns the system's high resolution time.

    Syntax

    hrtime(return_as_num)

    Parameter Values

    ParameterDescription
    return_as_numOptional. If set to TRUE, this function will return the high resolution time as array or number. Default is FALSE

    Technical Details

    Return Value: Returns nanoseconds or an array of integers
    PHP Version: 7.3+
    PHP Misc Reference PHP Misc Reference

    Example

    Set to false (default) - client aborts will cause the script to stop running: <?phpignore_user_abort(); ?> The output of the code above could be: 0

    Definition and Usage

    The ignore_user_abort() function sets whether a user should abort a script execution when he/she disconnects.

    Syntax

    ignore_user_abort(setting)

    Parameter Values

    ParameterDescription
    settingOptional. TRUE ignores user aborts in a script (the script will continue to run). This is FALSE by default, meaning that client aborts will cause the script to stop running

    Technical Details

    Return Value: Returns the previous value of the user-abort setting
    PHP Version: 4+
    PHP Misc Reference PHP Misc Reference

    Example

    Pack data into a binary string: <?phpecho pack("C3",80,72,80); ?> Try it Yourself »

    Definition and Usage

    The pack() function packs data into a binary string.

    Syntax

    pack(format,args+)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format to use when packing data. Possible values:
  • a - NUL-padded string
  • A - SPACE-padded string
  • h - Hex string, low nibble first
  • H - Hex string, high nibble first
  • c - signed char
  • C - unsigned char
  • s - signed short (always 16 bit, machine byte order)
  • S - unsigned short (always 16 bit, machine byte order)
  • n - unsigned short (always 16 bit, big endian byte order)
  • v - unsigned short (always 16 bit, little endian byte order)
  • i - signed integer (machine dependent size and byte order)
  • I - unsigned integer (machine dependent size and byte order)
  • l - signed long (always 32 bit, machine byte order)
  • L - unsigned long (always 32 bit, machine byte order)
  • N - unsigned long (always 32 bit, big endian byte order)
  • V - unsigned long (always 32 bit, little endian byte order)
  • q - signed long long (always 64 bit, machine byte order)
  • Q - unsigned long long (always 64 bit, machine byte order)
  • J - unsigned long long (always 64 bit, big endian byte order)
  • P - unsigned long long (always 64 bit, little endian byte order)
  • f - float (machine dependent size and representation)
  • g - float (machine dependent size, little endian byte order)
  • G - float (machine dependent size, big endian byte order)
  • d - double (machine dependent size and representation)
  • e - double (machine dependent size, little endian byte order)
  • E - double (machine dependent size, big endian byte order)
  • x - NUL byte
  • X - Back up one byte
  • Z - NUL-padded string
  • @ - NUL-fill to absolute position
  • args+Optional. Specifies one or more arguments to be packed

    Technical Details

    Return Value: Returns data in a binary string
    PHP Version: 4+
    Changelog: PHP 7.2 - float and double now supports both big and small endian.PHP 7.0.15 - The "E", "e", "G", "g" code was added.PHP 5.6.3 - The "Q", "q", "J", "P" code was added.PHP 5.5 - The "Z" code was added (holds the same functionality as "a" for Perl compatibility).

    More Examples

    Example

    Pack data into a binary string: <?phpecho pack("C*",80,72,80); ?> Try it Yourself » PHP Misc Reference PHP Misc Reference

    Example

    Return the source code of the "test.php" file with PHP comments and whitespace removed: <?php// PHP comment /* * Another PHP comment */ echo php_strip_whitespace ("test.php"); ?> If you select "View source" in the browser window, it will look like this: <?php echo php_strip_whitespace ("test.php"); ?>

    Definition and Usage

    The php_strip_whitespace() function returns the source code of the specified file with PHP comments and whitespace removed.

    Syntax

    php_strip_whitespace(filename)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file to strip

    Technical Details

    Return Value: Returns the stripped source code on success, or an empty string on failure. Note: This function only returns an empty string on versions before PHP 5.0.1.
    PHP Version: 5+
    PHP Misc Reference PHP Misc Reference

    Example

    Using a test file ("test.php") to output the file with the PHP syntax highlighted: <html> <body> <?php show_source("test.php"); ?> </body> </html> The browser output of the code above could be (depending on the content in your file): <html> <body> <?php echo ("test.php"); ?> </body></html> The HTML output of the code above could be (View Source): <html><body><code><span style="color: #000000">&lt;html&gt;<br />&lt;body&gt;<br /><span style="color: #0000BB">&lt;?php<br /></span><span style="color: #007700">echo&nbsp;(</span><span style="color: #DD0000">"test.php"</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?&gt; <br /></span>&lt;/body&gt;<br />&lt;/html&gt;</span></code></body></html> Try it Yourself »

    Definition and Usage

    The show_source() function outputs a file with the PHP syntax highlighted. The syntax is highlighted by using HTML tags. The colors used for highlighting can be set in the php.ini file or with the ini_set() function. show_source() is an alias of highlight_file(). Note: When using this function, the entire file will be displayed - including passwords and any other sensitive information!

    Syntax

    show_source(filename,return)

    Parameter Values

    ParameterDescription
    filenameRequired. Specifies the file to display
    returnOptional. If set to TRUE, this function will return the highlighted code as a string, instead of printing it out. Default is FALSE

    Technical Details

    Return Value: If the return parameter is set to TRUE, this function returns the highlighted code as a string instead of printing it out. Otherwise, it returns TRUE on success, or FALSE on failure
    PHP Version: 4+
    Changelog: As of PHP 4.2.1, this function is now also affected by safe_mode and open_basedir. However, safe_mode was removed in PHP 5.4.PHP 4.2 - The return parameter was added.
    PHP Misc Reference PHP Misc Reference

    Example

    Delay execution of the current script for 3 seconds: <?phpecho date('h:i:s') . "<br>"; //sleep for 3 seconds sleep(3); //start again echo date('h:i:s'); ?> Try it Yourself »

    Definition and Usage

    The sleep() function delays execution of the current script for a specified number of seconds. Note: This function throws an error if the specified number of seconds is negative.

    Syntax

    sleep(seconds)

    Parameter Values

    ParameterDescription
    secondsRequired. Specifies the number of seconds to delay the script

    Technical Details

    Return Value: Returns 0 on success, or FALSE on error.This function returns a non-zero value if the call was interrupted by a signal. On Windows, this value will always be 192, which is the value of the WAIT_IO_COMPLETION constant within the Windows API. On other platforms, the return value will be the number of seconds left to sleep.
    PHP Version: 4+
    Changelog: Before PHP 5.3.4, this function always returns NULL when sleep has occurred on Windows.
    PHP Misc Reference PHP Misc Reference

    Example

    Check the system load average. If it is over 0.8, stop script and display a message: <?php$loadtime = sys_getloadavg();if ($loadtime[0] > 0.80) { die('Sorry, server is busy.');}?>

    Definition and Usage

    The sys_getloadavg() function returns the system load average. This function returns an array with three numbers that represents the average system load over the last 1, 5 and 15 minutes. Note: This function does not work on Windows platforms.

    Syntax

    sys_getloadavg()

    Technical Details

    Return Value: Returns an array with three samples (last 1, 5 and 15 minutes)
    PHP Version: 5.1.3+
    PHP Misc Reference PHP Misc Reference

    Example

    Delay execution of the current script for 2,5 seconds: <?phpif (time_nanosleep(2,500000000) === true) { echo "Slept for 2,5 seconds"; } ?> Try it Yourself »

    Definition and Usage

    The time_nanosleep() function delays execution of the current script for a specified number of seconds and nanoseconds.

    Syntax

    time_nanosleep(seconds,nanoseconds)

    Parameter Values

    ParameterDescription
    secondsRequired. Specifies the number of seconds to delay the script
    nanosecondsRequired. Specifies the number of nanoseconds to delay the script (must be less than 1,000,000,000)

    Technical Details

    Return Value: Returns TRUE on success, or FALSE on failure.If the call was interrupted by a signal, an associative array will be returned with the number of seconds or nanoseconds remaining in the delay.
    PHP Version: 5+
    Changelog: This function did not work on Windows platforms prior PHP 5.3.0
    PHP Misc Reference PHP Misc Reference

    Example

    Let the script sleep for 3 seconds: <?phptime_sleep_until(time()+3);echo "Hello"; ?> Try it Yourself »

    Definition and Usage

    The time_sleep_until() function is used to make a script sleep until the specified time.

    Syntax

    time_sleep_until(timestamp)

    Parameter Values

    ParameterDescription
    timestampRequired. Specifies when the script should wake

    Technical Details

    Return Value: Returns TRUE on success, or FALSE on failure
    PHP Version: 5.1.0+
    Changelog: This function did not work on Windows platforms until PHP 5.3.0
    PHP Misc Reference PHP Misc Reference

    Example

    Generate a unique ID: <?phpecho uniqid(); ?> Try it Yourself »

    Definition and Usage

    The uniqid() function generates a unique ID based on the microtime (the current time in microseconds). Note: The generated ID from this function does not guarantee uniqueness of the return value! To generate an extremely difficult to predict ID, use the md5() function.

    Syntax

    uniqid(prefix,more_entropy)

    Parameter Values

    ParameterDescription
    prefixOptional. Specifies a prefix to the unique ID (useful if two scripts generate ids at exactly the same microsecond)
    more_entropyOptional. Specifies more entropy at the end of the return value. This will make the result more unique. When set to TRUE, the return string will be 23 characters. Default is FALSE, and the return string will be 13 characters long

    Technical Details

    Return Value: Returns the unique identifier, as a string
    PHP Version: 4+
    Changelog: The prefix parameter became optional in PHP 5.0.The limit of 114 characters long for prefix was raised in PHP 4.3.1.
    PHP Misc Reference PHP Misc Reference

    Example

    Unpack data from a binary string: <?php$data = "PHP"; print_r(unpack("C*",$data)); ?> Try it Yourself »

    Definition and Usage

    The unpack() function unpacks data from a binary string.

    Syntax

    unpack(format,data)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the format to use when unpacking data. Possible values:
  • a - NUL-padded string
  • A - SPACE-padded string
  • h - Hex string, low nibble first
  • H - Hex string, high nibble first
  • c - signed char
  • C - unsigned char
  • s - signed short (always 16 bit, machine byte order)
  • S - unsigned short (always 16 bit, machine byte order)
  • n - unsigned short (always 16 bit, big endian byte order)
  • v - unsigned short (always 16 bit, little endian byte order)
  • i - signed integer (machine dependent size and byte order)
  • I - unsigned integer (machine dependent size and byte order)
  • l - signed long (always 32 bit, machine byte order)
  • L - unsigned long (always 32 bit, machine byte order)
  • N - unsigned long (always 32 bit, big endian byte order)
  • V - unsigned long (always 32 bit, little endian byte order)
  • q - signed long long (always 64 bit, machine byte order)
  • Q - unsigned long long (always 64 bit, machine byte order)
  • J - unsigned long long (always 64 bit, big endian byte order)
  • P - unsigned long long (always 64 bit, little endian byte order)
  • f - float (machine dependent size and representation)
  • g - float (machine dependent size, little endian byte order)
  • G - float (machine dependent size, big endian byte order)
  • d - double (machine dependent size and representation)
  • e - double (machine dependent size, little endian byte order)
  • E - double (machine dependent size, big endian byte order)
  • x - NUL byte
  • X - Back up one byte
  • Z - NUL-padded string
  • @ - NUL-fill to absolute
  • dataRequired. Specifies the binary data to be unpacked
    offsetOptional. Specifies where to start unpacking from. Default is 0.

    Technical Details

    Return Value: Returns an array on success, or FALSE on failure.
    PHP Version: 4+
    Changelog: PHP 7.2 - float and double now supports both big and small endian.PHP 7.1 - Added the optional offset parameter.PHP 5.5.0 - The following changes were made for Perl compatibility: The "a" code now retains trailing NULL bytes.The "A" code now strips all trailing ASCII whitespace.The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.

    More Examples

    Example

    Unpack data: <?php$data = "PHP"; print_r(unpack("C*myint",$data)); ?> Try it Yourself »

    Example

    Unpack data: <?php$bin = pack("c2n2",0x1234,0x5678,65,66); print_r(unpack("c2chars/n2int",$bin)); ?> Try it Yourself » PHP Misc Reference PHP Misc Reference

    Example

    Delay execution of the current script for 3 seconds (3000000 microseconds): <?phpecho date('h:i:s') . "<br>";//sleep for 3 seconds usleep(3000000);//start againecho date('h:i:s'); ?> Try it Yourself »

    Definition and Usage

    The usleep() function delays execution of the current script for a specified number of microseconds (a microsecond equals one millionth of a second).

    Syntax

    usleep(microseconds)

    Parameter Values

    ParameterDescription
    microsecondsRequired. Specifies the number of microseconds to delay the script

    Technical Details

    Return Value: No value is returned
    PHP Version: 4+
    Changelog: This function did not work on Windows platforms until PHP 5
    PHP Misc Reference

    MySQLi Introduction

    The MySQLi functions allows you to access MySQL database servers. Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.

    Installation / Runtime Configuration

    For the MySQLi functions to be available, you must compile PHP with support for the MySQLi extension. The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0. For installation details, go to: http://php.net/manual/en/mysqli.installation.php For runtime configuration details, go to: http://php.net/manual/en/mysqli.configuration.php

    MySQLi Functions

    FunctionDescription
    affected_rows()Returns the number of affected rows in the previous MySQL operation
    autocommit()Turns on or off auto-committing database modifications
    begin_transaction()Starts a transaction
    change_user()Changes the user of the specified database connection
    character_set_name()Returns the default character set for the database connection
    close()Closes a previously opened database connection
    commit()Commits the current transaction
    connect()Opens a new connection to the MySQL server
    connect_errno()Returns the error code from the last connection error
    connect_error()Returns the error description from the last connection error
    data_seek()Adjusts the result pointer to an arbitrary row in the result-set
    debug()Performs debugging operations
    dump_debug_info()Dumps debugging info into the log
    errno()Returns the last error code for the most recent function call
    error()Returns the last error description for the most recent function call
    error_list()Returns a list of errors for the most recent function call
    fetch_all()Fetches all result rows as an associative array, a numeric array, or both
    fetch_array()Fetches a result row as an associative, a numeric array, or both
    fetch_assoc()Fetches a result row as an associative array
    fetch_field()Returns the next field in the result-set, as an object
    fetch_field_direct()Returns meta-data for a single field in the result-set, as an object
    fetch_fields()Returns an array of objects that represent the fields in a result-set
    fetch_lengths()Returns the lengths of the columns of the current row in the result-set
    fetch_object()Returns the current row of a result-set, as an object
    fetch_row()Fetches one row from a result-set and returns it as an enumerated array
    field_count()Returns the number of columns for the most recent query
    field_seek()Sets the field cursor to the given field offset
    get_charset()Returns a character set object
    get_client_info()Returns the MySQL client library version
    get_client_stats()Returns statistics about client per-process
    get_client_version()Returns the MySQL client library version as an integer
    get_connection_stats()Returns statistics about the client connection
    get_host_info()Returns the MySQL server hostname and the connection type
    get_proto_info()Returns the MySQL protocol version
    get_server_info()Returns the MySQL server version
    get_server_version()Returns the MySQL server version as an integer
    info()Returns information about the last executed query
    init()Initializes MySQLi and returns a resource for use with real_connect()
    insert_id()Returns the auto-generated id from the last query
    kill()Asks the server to kill a MySQL thread
    more_results()Checks if there are more results from a multi query
    multi_query()Performs one or more queries on the database
    next_result()Prepares the next result-set from multi_query()
    options()Sets extra connect options and affect behavior for a connection
    ping()Pings a server connection, or tries to reconnect if the connection has gone down
    poll()Polls connections
    prepare()Prepares an SQL statement for execution
    query()Performs a query against a database
    real_connect()Opens a new connection to the MySQL server
    real_escape_string()Escapes special characters in a string for use in an SQL statement
    real_query()Executes a single SQL query
    reap_async_query()Returns result from an async SQL query
    refresh()Refreshes/flushes tables or caches, or resets the replication server information
    rollback()Rolls back the current transaction for the database
    select_db()Select the default database for database queries
    set_charset()Sets the default client character set
    set_local_infile_default()Unsets user defined handler for load local infile command
    set_local_infile_handler()Set callback function for LOAD DATA LOCAL INFILE command
    sqlstate()Returns the SQLSTATE error code for the error
    ssl_set()Used to establish secure connections using SSL
    stat()Returns the current system status
    stmt_init()Initializes a statement and returns an object for use with stmt_prepare()
    store_result()Transfers a result-set from the last query
    thread_id()Returns the thread ID for the current connection
    thread_safe()Returns whether the client library is compiled as thread-safe
    use_result()Initiates the retrieval of a result-set from the last query executed
    warning_count()Returns the number of warnings from the last query in the connection
    PHP MySQLi Reference

    Example - Object Oriented style

    Return the number of affected rows from different queries: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform queries and print out affected rows$mysqli -> query("SELECT * FROM Persons");echo "Affected rows: " . $mysqli -> affected_rows; $mysqli -> query("DELETE FROM Persons WHERE Age>32");echo "Affected rows: " . $mysqli -> affected_rows; $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.

    Syntax

    Object oriented style:

    $mysqli -> affected_rows

    Procedural style:

    mysqli_affected_rows(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: The number of rows affected. -1 indicates that the query returned an error
    PHP Version: 5+

    Example - Procedural style

    Return the number of affected rows from different queries: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }// Perform queries and print out affected rowsmysqli_query($con, "SELECT * FROM Persons");echo "Affected rows: " . mysqli_affected_rows($con); mysqli_query($con, "DELETE FROM Persons WHERE Age>32");echo "Affected rows: " . mysqli_affected_rows($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Turn off auto-committing, make some queries, then commit the queries: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Turn autocommit off$mysqli -> autocommit(FALSE); // Insert some values $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli -> commit()) { echo "Commit transaction failed"; exit();}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The autocommit() / mysqli_autocommit() function turns on or off auto-committing database modifications. Tip: Also look at the commit() function, which commits the current transaction for the specified database connection, and the rollback() function, which rolls back the current transaction.

    Syntax

    Object oriented style:

    $mysqli -> autocommit(mode)

    Procedural style:

    mysqli_autocommit(connection, mode)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    modeRequired. FALSE turns auto-commit off. TRUE turns auto-commit on (and commits any waiting queries)

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Turn off auto-committing, make some queries, then commit the queries: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }// Turn autocommit offmysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli_commit($con)) { echo "Commit transaction failed"; exit();}// Close connection mysqli_close($con);?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Change the user of the specified database connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Reset all and select a new database $mysqli -> change_user("my_user", "my_password", "test"); $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The change_user() / mysqli_change_user() function changes the user of the specified database connection, and sets the current database.

    Syntax

    Object oriented style:

    $mysqli -> change_user(username, password, dbname)

    Procedural style:

    mysqli_change_user(connection, username, password, dbname)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    usernameRequired. Specifies the MySQL user name
    passwordRequired. Specifies the MySQL password
    dbnameRequired. Specifies the database to change to

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Change the user of the specified database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }// Reset all and select a new database mysqli_change_user($con, "my_user", "my_password", "test"); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the default character set for the database connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$charset = $mysqli -> character_set_name();echo "Default character set is: " . $charset; $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The character_set_name() / mysqli_character_set_name() function returns the default character set for the database connection.

    Syntax

    Object oriented style:

    $mysqli -> character_set_name()

    Procedural style:

    mysqli_character_set_name(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: The default character set for the specified connection
    PHP Version: 5+

    Example - Procedural style

    Return the default character set for the database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$charset=mysqli_character_set_name($con);echo "Default character set is: " . $charset;mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Close a previously opened database connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// ....some PHP code...$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The close() / mysqli_close() function closes a previously opened database connection.

    Syntax

    Object oriented style:

    $mysqli -> close()

    Procedural style:

    mysqli_close(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to close

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Close a previously opened database connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; } // ....some PHP code... mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Turn off auto-committing, make some queries, then commit the queries: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Turn autocommit off$mysqli -> autocommit(FALSE); // Insert some values $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli -> commit()) { echo "Commit transaction failed"; exit();}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The commit() / mysqli_commit() function commits the current transaction for the specified database connection. Tip: Also look at the autocommit() function, which turns on or off auto-committing database modifications, and the rollback() function, which rolls back the current transaction.

    Syntax

    Object oriented style:

    $mysqli -> commit(flags, name)

    Procedural style:

    mysqli_commit(connection, flags, name)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    flagsOptional. A constant:
  • MYSQLI_TRANS_COR_AND_CHAIN - Appends "AND CHAIN"
  • MYSQLI_TRANS_COR_AND_NO_CHAIN - Appends "AND NO CHAIN"
  • MYSQLI_TRANS_COR_RELEASE - Appends "RELEASE"
  • MYSQLI_TRANS_COR_NO_RELEASE - Appends "NO RELEASE"
  • nameOptional. COMMIT/*name*/ is executed if this parameter is specified

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.5: Added the flags and name parameters

    Example - Procedural style

    Turn off auto-committing, make some queries, then commit the queries: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }// Turn autocommit offmysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli_commit($con)) { echo "Commit transaction failed"; exit();}// Close connection mysqli_close($con);?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Open a new connection to the MySQL server: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }?> Look at example of procedural style at the bottom.

    Definition and Usage

    The connect() / mysqli_connect() function opens a new connection to the MySQL server.

    Syntax

    Object oriented style:

    $mysqli -> new mysqli(host, username, password, dbname, port, socket)

    Procedural style:

    mysqli_connect(host, username, password, dbname, port, socket)

    Parameter Values

    ParameterDescription
    hostOptional. Specifies a host name or an IP address
    usernameOptional. Specifies the MySQL username
    passwordOptional. Specifies the MySQL password
    dbnameOptional. Specifies the default database to be used
    portOptional. Specifies the port number to attempt to connect to the MySQL server
    socketOptional. Specifies the socket or named pipe to be used

    Technical Details

    Return Value: Returns an object representing the connection to the MySQL server
    PHP Version: 5+

    Example - Procedural style

    Open a new connection to the MySQL server: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();} ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return an error code from the last connection error, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }?> Look at example of procedural style at the bottom.

    Definition and Usage

    The connect_errno / mysqli_connect_errno() function returns the error code from the last connection error, if any.

    Syntax

    Object oriented style:

    $mysqli -> connect_errno

    Procedural style:

    mysqli_connect_errno()

    Technical Details

    Return Value: Returns an error code value. Zero if no error occurred
    PHP Version: 5+

    Example - Procedural style

    Return an error code from the last connection error, if any: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();} ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the error description from the last connection error, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }?> Look at example of procedural style at the bottom.

    Definition and Usage

    The connect_error / mysqli_connect_error() function returns the error description from the last connection error, if any.

    Syntax

    Object oriented style:

    $mysqli -> connect_error

    Procedural style:

    mysqli_connect_error();

    Technical Details

    Return Value: Returns a string that describes the error. NULL if no error occurred
    PHP Version: 5+

    Example - Procedural style

    Return the error description from the last connection error, if any: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();} ?> PHP MySQLi Reference PHP MySQLi Reference

    Example

    Seek to row number 15 in the result-set: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Seek to row number 15 mysqli_data_seek($result,14); // Fetch row $row=mysqli_fetch_row($result); printf ("Lastname: %s Age: %s\n", $row[0], $row[1]); // Free result set mysqli_free_result($result);} mysqli_close($con); ?>

    Definition and Usage

    The mysqli_data_seek() function adjusts the result pointer to an arbitrary row in the result-set.

    Syntax

    mysqli_data_seek(result,offset);

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    offsetRequired. Specifies the field offset. Must be between 0 and the total number of rows - 1

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example

    Create a trace file in "/temp/client.trace" on the local machine: <?php mysqli_debug("d:t:o,/temp/client.trace");?>

    Definition and Usage

    The mysqli_debug() function is used to perform debugging operations. Note: In order to use this function, you must compile the MySQL client library to support debugging.

    Syntax

    mysqli_debug(message);

    Parameter Values

    ParameterDescription
    messageRequired. A string that represents the debugging operation to perform

    Technical Details

    Return Value: TRUE
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Dump debug info into the log: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); $mysqli -> dump_debug_info();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The dump_debug_info() / mysqli_dump_debug_info() function dumps debugging info into the log.

    Syntax

    Object oriented style:

    $mysqli -> dump_debug_info()

    Procedural style:

    mysqli_dump_debug_info(link);

    Parameter Values

    ParameterDescription
    linkRequired. A link identifier returned by connect() or init()

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Dump debug info into the log: <?php$con = mysqli_connect("localhost","my_user","my_password","my_db"); mysqli_dump_debug_info($con);?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the last error code for the most recent function call, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform a query, check for errorif (!$mysqli -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Errorcode: " . $mysqli -> errno); } $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The errno / mysqli_errno() function returns the last error code for the most recent function call, if any.

    Syntax

    Object oriented style:

    $mysqli -> errno

    Procedural style:

    mysqli_errno(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an error code value. Zero if no error occurred
    PHP Version: 5+

    Example - Procedural style

    Return the last error code for the most recent function call, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}// Perform a query, check for errorif (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Errorcode: " . mysqli_errno($con)); } mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the last error description for the most recent function call, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform a query, check for errorif (!$mysqli -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . $mysqli -> error); } $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The error / mysqli_error() function returns the last error description for the most recent function call, if any.

    Syntax

    Object oriented style:

    $mysqli -> error

    Procedural style:

    mysqli_error(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns a string with the error description. " if no error occurred
    PHP Version: 5+

    Example - Procedural Oriented style

    Return the last error description for the most recent function call, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}// Perform a query, check for errorif (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . mysqli_error($con));} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return a list of errors from the last executed command, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform a query, check for errorif (!$mysqli -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { print_r($mysqli -> error_list); } $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The error_list / mysqli_error_list() function returns a list of errors from the last executed command, if any.

    Syntax

    Object oriented style:

    $mysqli -> error_list

    Procedural style:

    mysqli_error_list(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns a list of errors as an associative array; with errno (error code), error (error text), and sqlstate
    PHP Version: 5.4+

    Example - Procedural style

    Return a list of errors from the last executed command, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }// Perform a query, check for errorif (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { print_r(mysqli_error_list($con));} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Fetch all rows and return the result-set as an associative array: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";$result -> $mysqli -> query($sql); // Fetch all$result -> fetch_all(MYSQLI_ASSOC);// Free result set$result -> free_result(); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both. Note: This function is available only with MySQL Native Driver.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_all(resulttype)

    Procedural style:

    mysqli_fetch_all(result, resulttype)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    resulttypeOptional. Specifies what type of array that should be produced. Can be one of the following values:
  • MYSQLI_ASSOC
  • MYSQLI_NUM (this is default)
  • MYSQLI_BOTH
  • Technical Details

    Return Value: Returns an array of associative or numeric arrays holding the result rows
    PHP Version: 5.3+

    Example - Procedural style

    Fetch all rows and return the result-set as an associative array: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con, $sql);// Fetch allmysqli_fetch_all($result, MYSQLI_ASSOC); // Free result setmysqli_free_result($result); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Fetch a result row as a numeric array and as an associative array: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";$result -> $mysqli -> query($sql); // Numeric array $row = $result -> fetch_array(MYSQLI_NUM);printf ("%s (%s)\n", $row[0], $row[1]);// Associative array $row = $result -> fetch_array(MYSQLI_ASSOC);printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set$result -> free_result(); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_array() / mysqli_fetch_array() function fetches a result row as an associative array, a numeric array, or both. Note: Fieldnames returned from this function are case-sensitive.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_array(resulttype)

    Procedural style:

    mysqli_fetch_array(result,resulttype)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    resulttypeOptional. Specifies what type of array that should be produced. Can be one of the following values:
  • MYSQLI_ASSOC
  • MYSQLI_NUM
  • MYSQLI_BOTH (this is default)
  • Technical Details

    Return Value: Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result-set
    PHP Version: 5+

    Example - Procedural style

    Fetch a result row as a numeric array and as an associative array: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con,$sql);// Numeric array $row = mysqli_fetch_array($result, MYSQLI_NUM);printf ("%s (%s)\n", $row[0], $row[1]);// Associative array $row = mysqli_fetch_array($result, MYSQLI_ASSOC);printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result setmysqli_free_result($result); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Fetch a result row as an associative array: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = $mysqli -> query($sql); // Associative array $row = $result -> fetch_assoc();printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result set$result -> free_result(); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_assoc() / mysqli_fetch_assoc() function fetches a result row as an associative array. Note: Fieldnames returned from this function are case-sensitive.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_assoc()

    Procedural style:

    mysqli_fetch_assoc(result)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

    Technical Details

    Return Value: Returns an associative array of strings representing the fetched row. NULL if there are no more rows in result-set
    PHP Version: 5+

    Example - Procedural style

    Fetch a result row as an associative array: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; $result = mysqli_query($con, $sql);// Associative array $row = mysqli_fetch_assoc($result);printf ("%s (%s)\n", $row["Lastname"], $row["Age"]); // Free result setmysqli_free_result($result); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the next field (column) in the result-set, then print each field's name, table, and max length: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { // Get field information for all fields while ($fieldinfo = $result -> fetch_field()) { printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); } $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_field() / mysqli_fetch_field() function returns the next field (column) in the result-set, as an object.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_field()

    Procedural style:

    mysqli_fetch_field(result)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

    Technical Details

    Return Value: Returns an object containing field definition information. FALSE if no info is available. The object has the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • def - reserved for default values, currently always "
  • db - database (new in PHP 5.3.6)
  • catalog - catalog name, always "def" (since PHP 5.3.6)
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
  • PHP Version: 5+

    Example - Procedural style

    Return the next field (column) in the result-set, then print each field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Get field information for all fields while ($fieldinfo = mysqli_fetch_field($result)) { printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("max. Len: %d\n", $fieldinfo -> max_length); } mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return meta-data for a single field in the result-set, then print the field's name, table, and max length: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { // Get field information for column "Age" $fieldinfo = $result -> fetch_field_direct(1); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_field_direct() / mysqli_fetch_field_direct() function returns meta-data for a single field in a result-set, as an object.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_field_direct(fieldnr)

    Procedural style:

    mysqli_fetch_field_direct(result, fieldnr)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    fieldnrRequired. Specifies the field number. Must be an integer from 0 to number of fields-1

    Technical Details

    Return Value: Returns an object containing field definition information. FALSE if no info is available. The object has the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • def - default value for this field
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
  • PHP Version: 5+

    Example - Procedural style

    Return meta-data for a single field in the result-set, then print the field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Get field information for column "Age" $fieldinfo = mysqli_fetch_field_direct($result, 1); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return an array of objects that represent the fields in a result-set, then print each field's name, table, and max length: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { // Get field information for all fields $fieldinfo = $result -> fetch_fields(); foreach ($fieldinfo as $val) { printf("Name: %s\n", $val -> name); printf("Table: %s\n", $val -> table); printf("Max. Len: %d\n", $val -> max_length); } $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_fields() / mysqli_fetch_fields() function returns an array of objects that represent the fields in a result-set.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_fields()

    Procedural style:

    mysqli_fetch_fields(result)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

    Technical Details

    Return Value: Returns an array of objects containing field definition information. FALSE if no info is available. The objects have the following properties:
  • name - name of the column
  • orgname - original column name (if an alias is specified)
  • table - name of table
  • orgtable - original table name (if an alias is specified)
  • max_length - maximum width of field
  • length - width of field as specified in table definition
  • charsetnr - character set number for the field
  • flags - bit-flags for the field
  • type - data type used for the field
  • decimals - for integer fields; the number of decimals used
  • PHP Version: 5+

    Example - Procedural style

    Return an array of objects that represent the fields in a result-set, then print each field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con , $sql)) { // Get field information for all fields $fieldinfo = mysqli_fetch_fields($result); foreach ($fieldinfo as $val) { printf("Name: %s\n", $val->name); printf("Table: %s\n", $val->table); printf("Max. Len: %d\n", $val->max_length); } mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the length of the fields of the current row in the result-set: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT * FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { $row = $result -> fetch_row(); // Display field lengths foreach ($result -> lengths as $i => $val) { printf("Field %2d has length: %2d\n", $i + 1, $val); } $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The lengths / mysqli_fetch_lengths() function returns the length of the fields of the current row in the result-set.

    Syntax

    Object oriented style:

    $mysqli_result -> lengths

    Procedural style:

    mysqli_fetch_lengths(result)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

    Technical Details

    Return Value: Returns an array of integers that represents the size of each field (column). FALSE if an error occurs
    PHP Version: 5+

    Example - Procedural style

    Return the length of the fields of the current row in the result-set: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT * FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { $row = mysqli_fetch_row($result); // Display field lengths foreach (mysqli_fetch_lengths($result) as $i => $val) { printf("Field %2d has length: %2d\n", $i+1, $val); } mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the current row of a result set, then print each field's value: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { while ($obj = $result -> fetch_object()) { printf("%s (%s)\n", $obj->Lastname, $obj->Age); } $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_object() / mysqli_fetch_object() function returns the current row of a result-set, as an object. Note: Fieldnames returned from this function are case-sensitive.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_object(classname, params)

    Procedural style:

    mysqli_fetch_object(result, classname, params)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    classnameOptional. Specifies the name of the class to instantiate, set the properties of, and return
    paramsOptional. Specifies an array of parameters to pass to the constructor for classname objects

    Technical Details

    Return Value: Returns an object with string properties for the fetched row. NULL if there are no more rows in the result set
    PHP Version: 5+
    Changelog: The ability to return as a different object was added in PHP 5.0.0

    Example - Procedural style

    Return the current row of a result set, then print each field's value: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { while ($obj = mysqli_fetch_object($result)) { printf("%s (%s)\n", $obj->Lastname, $obj->Age); } mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Fetch rows from a result-set: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { while ($row = $result -> fetch_row()) { printf ("%s (%s)\n", $row[0], $row[1]); } $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.

    Syntax

    Object oriented style:

    $mysqli_result -> fetch_row()

    Procedural style:

    mysqli_fetch_row(result)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

    Technical Details

    Return Value: Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result set
    PHP Version: 5+

    Example - Procedural style

    Fetch rows from a result-set: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con, $sql)) { // Fetch one and one row while ($row = mysqli_fetch_row($result)) { printf ("%s (%s)\n", $row[0], $row[1]); } mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Assume we have a table named "Friends" (with 3 columns and 20 rows). This example returns the number of columns for the most recent query: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$mysqli -> query("SELECT * FROM Friends");// Get number of columns - will return 3 $mysqli -> field_count(); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The field_count() / mysqli_field_count() function returns the number of columns for the most recent query.

    Syntax

    Object oriented style:

    $mysqli -> field_count()

    Procedural style:

    mysqli_field_count(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an integer that represents the number of columns in the result set
    PHP Version: 5+

    Example - Procedural style

    Assume we have a table named "Friends" (with 3 columns and 20 rows). This example returns the number of columns for the most recent query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}mysqli_query($con, "SELECT * FROM Friends");// Get number of columns - will return 3mysqli_field_count($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Set the field cursor to the second column ("Age") in the result-set, get field info with fetch_field(), then print the field's name, table, and max length: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = $mysqli -> query($sql)) { // Get field information for second column $result = field_seek(1); $fieldinfo = $result -> fetch_field(); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("Max. Len: %d\n", $fieldinfo -> max_length); $result -> free_result();} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The field_seek() / mysqli_field_seek() function sets the field cursor to the given field offset.

    Syntax

    Object oriented style:

    $mysqli_result -> field_seek(fieldnr)

    Procedural style:

    mysqli_field_seek(result, fieldnr)

    Parameter Values

    ParameterDescription
    resultRequired. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
    fieldnrRequired. Specifies the field number. Must be an integer from 0 to number of fields-1

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Set the field cursor to the second column ("Age") in the result-set, get field info with mysqli_fetch_field(), then print the field's name, table, and max length: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}$sql="SELECT Lastname, Age FROM Persons ORDER BY Lastname"; if ($result = mysqli_query($con,$sql)) { // Get field information for second column mysqli_field_seek($result, 1); $fieldinfo = mysqli_fetch_field($result); printf("Name: %s\n", $fieldinfo -> name); printf("Table: %s\n", $fieldinfo -> table); printf("max. Len: %d\n", $fieldinfo -> max_length); mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return a character set object, with several properties: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }var_dump($mysqli -> get_charset()); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The get_charset() / mysqli_get_charset() function returns a character set object with several properties for the current character set.

    Syntax

    Object oriented style:

    $mysqli -> get_charset()

    Procedural style:

    mysqli_get_charset(connection);

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns a character set object with the following properties:
  • charset - character set name
  • collation - collation name
  • dir - directory the charset was fetched from or "
  • min_length - min character length in bytes
  • max_length - max character length in bytes
  • number - internal character set number
  • state - character set status
  • PHP Version: 5.1+

    Example - Procedural style

    Return a character set object, with several properties: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }var_dump(mysqli_get_charset($con)); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example

    Return the MySQL client library version: <?php echo mysqli_get_client_info();?>

    Definition and Usage

    The get_client_info() / mysqli_get_client_info() function returns the MySQL client library version.

    Syntax

    Object oriented style:

    $mysqli -> get_client_info()

    Procedural style:

    mysqli_get_client_info(connection)

    Parameter Values

    ParameterDescription
    connectionOptional. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns a string that represents the MySQL client library version
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example

    Return stats about client per-process: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); print_r(mysqli_get_client_stats()); ?>

    Definition and Usage

    The mysqli_get_client_stats() function returns client per-process statistics.

    Syntax

    mysqli_get_client_stats()

    Technical Details

    Return Value: An array with client stats on success. FALSE on failure
    PHP Version: 5.3+
    PHP MySQLi Reference PHP MySQLi Reference

    Example

    Return the MySQL client version as an integer: <?php echo mysqli_get_client_version(); ?>

    Definition and Usage

    The client_version / mysqli_get_client_version() function returns the MySQL client version as an integer. The MySQL client version is returned in the following format: main_version*10000 + minor_version*100 + sub_version. So, version 6.3.0 is returned as 60300.

    Syntax

    Object oriented style:

    $mysqli -> client_version

    Procedural style:

    mysqli_get_client_version(connection)

    Parameter Values

    ParameterDescription
    connectionOptional. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an integer that represents the MySQL client version
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example

    Return stats about the client connection: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); print_r(mysqli_get_connection_stats($con)); ?>

    Definition and Usage

    The mysqli_get_connection_stats() function returns statistics about the client connection.

    Syntax

    Object oriented style:

    $mysqli -> get_connection_stats()

    Procedural style:

    mysqli_get_connection_stats(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an array with connection stats on success. FALSE on failure
    PHP Version: 5.3+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the server hostname and connection type: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo $mysqli -> host_info(); $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The host_info() / mysqli_get_host_info() function returns the MySQL server hostname and the connection type.

    Syntax

    Object oriented style:

    $mysqli -> host_info

    Procedural style:

    mysqli_get_host_info(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns a string that represents the MySQL server hostname and the connection type
    PHP Version: 5+

    Example - Procedural style

    Return the server hostname and connection type: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}echo mysqli_get_host_info($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the MySQL protocol version: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo $mysqli -> protocol_version; $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The mysqli_get_proto_info() function returns the MySQL protocol version.

    Syntax

    Object oriented style:

    $mysqli -> protocol_version

    Procedural style:

    mysqli_get_proto_info(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an integer that represents the MySQL protocol version
    PHP Version: 5+

    Example - Procedural style

    Return the MySQL protocol version: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}echo mysqli_get_proto_info($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the MySQL protocol version: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo $mysqli -> server_info; $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The server_info / mysqli_get_server_info() function returns the MySQL server version.

    Syntax

    Object oriented style:

    $mysqli -> server_info

    Procedural style:

    mysqli_get_server_info(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: A string that represents the MySQL server version
    PHP Version: 5+

    Example - Procedural style

    Return the MySQL server version: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}echo mysqli_get_server_info($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the MySQL server version as an integer: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo $mysqli -> server_version; $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The server_version / mysqli_get_server_version() function returns the MySQL server version as an integer. The server version is returned in the following format: main_version*10000 + minor_version*100 + sub_version. So, version 6.3.0 is returned as 60300.

    Syntax

    Object oriented style:

    $mysqli -> server_version

    Procedural style:

    mysqli_get_server_version(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an integer that represents the MySQL server version
    PHP Version: 5+

    Example - Procedural style

    Return the MySQL server version as an integer: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }echo mysqli_get_server_version($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return information about the last executed query: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform some queries$mysqli -> query("CREATE TABLE testPersons LIKE Persons");$mysqli -> query("INSERT INTO testPersons SELECT * FROM Persons ORDER BY LastName");echo $mysqli -> info; $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The info / mysqli_info() function returns information about the last executed query. This function works with the following query types:
  • INSERT INTO...SELECT...
  • INSERT INTO...VALUES (...),(...),(...)
  • LOAD DATA INFILE ...
  • ALTER TABLE ...
  • UPDATE ...
  • Syntax

    Object oriented style:

    $mysqli -> info

    Procedural style:

    mysqli_info(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: A string that contains additional info about the last executed query
    PHP Version: 5+

    Example - Procedural style

    Return information about the last executed query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}// Perform som queriesmysqli_query($con, "CREATE TABLE testPersons LIKE Persons");mysqli_query($con, "INSERT INTO testPersons SELECT * FROM Persons ORDER BY LastName");echo mysqli_info($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example

    Use of the mysqli_init() function: <?php$con = mysqli_init();if (!$con) { die("mysqli_init failed");} if (!mysqli_real_connect($con,"localhost","my_user","my_password","my_db")) { die("Connect Error: " . mysqli_connect_error());} mysqli_close($con);?>

    Definition and Usage

    The init / mysqli_init() function initializes MySQLi and returns an object to use with the mysqli_real_connect() function.

    Syntax

    Object oriented style:

    $mysqli -> init

    Procedural style:

    mysqli_init()

    Technical Details

    Return Value: An object to use with the mysqli_real_connect() function
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Assume that the "Persons" table has an auto-generated id field. Return the id from the last query: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$mysqli -> query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");// Print auto-generated idecho "New record has id: " . $mysqli -> insert_id; $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.

    Syntax

    Object oriented style:

    $mysqli -> insert_id

    Procedural style:

    mysqli_insert_id(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: An integer that represents the value of the AUTO_INCREMENT field updated by the last query. Returns zero if there were no update or no AUTO_INCREMENT field
    PHP Version: 5+

    Example - Procedural style

    Assume that the "Persons" table has an auto-generated id field. Return the id from the last query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");// Print auto-generated idecho "New record has id: " . mysqli_insert_id($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the thread ID for the current connection, then kill the connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Get thread id$t_id = $mysqli -> thread_id;// Kill connection$mysqli -> kill($t_id);$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The kill() / mysqli_kill() function asks the server to kill a MySQL thread specified by the processid parameter.

    Syntax

    Object oriented style:

    $mysqli -> kill(processid)

    Procedural style:

    mysqli_kill(connection, processid)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    processidRequired. The thread ID returned from thread_id()

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example

    Return the thread ID for the current connection, then kill the connection: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}// Get thread id$t_id=mysqli_thread_id($con);// Kill connectionmysqli_kill($con, $t_id); mysqli_close($con);?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Perform multiple queries against the database: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif ($mysqli -> multi_query($sql)) { do { // Store first result set if ($result = $mysqli -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($mysqli -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($mysqli -> next_result());}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The more_results() / mysqli_more_results() function checks if there are any more query results from a multi query.

    Syntax

    Object oriented style:

    $mysqli -> more_results()

    Procedural style:

    mysqli_more_results(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: TRUE if there is one or more result sets available from multi_query(). FALSE otherwise
    PHP Version: 5+

    Example - Procedural style

    Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con));}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Perform multiple queries against the database: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif ($mysqli -> multi_query($sql)) { do { // Store first result set if ($result = $mysqli -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($mysqli -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($mysqli -> next_result());}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The multi_query() / mysqli_multi_query() function performs one or more queries against the database. The queries are separated with a semicolon.

    Syntax

    Object oriented style:

    $mysqli -> multi_query(query)

    Procedural style:

    mysqli_multi_query(connection, query)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    queryRequired. Specifies one or more queries, separated with semicolon

    Technical Details

    Return Value: FALSE if the first query fails
    PHP Version: 5+

    Example - Procedural style

    Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con));}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Perform multiple queries against the database: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif ($mysqli -> multi_query($sql)) { do { // Store first result set if ($result = $mysqli -> store_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> free_result(); } // if there are more result-sets, the print a divider if ($mysqli -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($mysqli -> next_result());}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The next_result() / mysqli_next_result() function prepares the next result-set from multi_query().

    Syntax

    Object oriented style:

    $mysqli -> next_result()

    Procedural style:

    mysqli_next_result(connection);

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Perform multiple queries against the database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_store_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con));}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Set extra connect options: <?php$mysqli = mysqli_init();if (!$mysqli) { die("mysqli_init failed");} // Specify connection timeout$con -> options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);// Specify read options from named file instead of my.cnf$con -> options(MYSQLI_READ_DEFAULT_FILE, "myfile.cnf");$con -> real_connect("localhost","my_user","my_password","my_db");?> Look at example of procedural style at the bottom.

    Definition and Usage

    The options() / mysqli_options() function is used to set extra connect options and affect behavior for a connection. Note: This function should be called after init() and before real_connect().

    Syntax

    Object oriented style:

    $mysqli -> options(option, value)

    Procedural style:

    mysqli_options(connection, option, value)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    optionRequired. Specifies the option to set. Can be one of the following values:
  • MYSQLI_OPT_CONNECT_TIMEOUT - Set connection timeout in seconds
  • MYSQLI_OPT_LOCAL_INFILE - Enable/Disable use of LOAD LOCAL INFILE
  • MYSQLI_INIT_COMMAND - Set a command to execute after connecting to MySQL server
  • MYSQLI_READ_DEFAULT_FILE - Set read options from named file instead of my.cnf
  • MYSQLI_READ_DEFAULT_GROUP - Set read options from named group from my.cnf or the file specified in MYSQLI_READ_DEFAULT_FILE
  • MYSQLI_SERVER_PUBLIC_KEY - Set RSA public key file used with SHA-256 based authentication
  • MYSQLI_OPT_NET_CMD_BUFFER_SIZE - only for mysqlnd
  • MYSQLI_OPT_NET_READ_BUFFER_SIZE - only for mysqlnd
  • MYSQLI_OPT_INT_AND_FLOAT_NATIVE - only for mysqlnd
  • MYSQLI_OPT_SSL_VERIFY_SERVER_CERT - only for mysqlnd
  • valueRequired. Specifies the value for the option

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.5: Added MYSQLI_SERVER_PUBLIC_KEY optionPHP 5.3: Added MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options

    Example - Procedural style

    Set extra connect options: <?php$con = mysqli_init();if (!$con) { die("mysqli_init failed");} // Specify connection timeoutmysqli_options($con, MYSQLI_OPT_CONNECT_TIMEOUT, 10);// Specify read options from named file instead of my.cnf mysqli_options($con, MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); mysqli_real_connect($con,"localhost","my_user","my_password","my_db");?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Ping a server connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Check if server is aliveif ($mysqli -> ping()) { echo "Connection is ok!";} else { echo "Error: ". $mysqli -> error);}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The ping() / mysqli_ping() function pings a server connection, to check if the server is alive. It also tries to reconnect - if the connection has gone down.

    Syntax

    Object oriented style:

    $mysqli -> ping()

    Procedural style:

    mysqli_ping(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Ping a server connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit();}// Check if server is aliveif (mysqli_ping($con)) { echo "Connection is ok!";} else { echo "Error: ". mysqli_error($con);}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Definition and Usage

    The poll() / mysqli_poll() function is used to poll connections.

    Syntax

    Object oriented style:

    $mysqli -> poll(read, error, reject, seconds, microseconds)

    Procedural style:

    mysqli_poll(read, error, reject, seconds, microseconds)

    Parameter Values

    ParameterDescription
    readRequired. Specifies a list of connections to check for outstanding results that can be read
    errorRequired. Specifies a list of connections on which an error occurred, like query failure or lost connection
    rejectRequired. Specifies a list of connections rejected because no asynchronous query has been run on for which the function could poll results
    secondsRequired. Specifies the maximum number of seconds to wait
    microsecondsOptional. Specifies the maximum number of microseconds to wait. Default is 0

    Technical Details

    Return Value: The number of ready connections on success. FALSE on failure
    PHP Version: 5.3+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Prepare an SQL statement for execution: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// prepare and bind$stmt = $mysqli -> prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");$stmt -> bind_param("sss", $firstname, $lastname, $email);// set parameters and execute$firstname = "John";$lastname = "Doe";$email = "john@example.com";$stmt -> execute(); $firstname = "Mary";$lastname = "Moe";$email = "mary@example.com"; $stmt -> execute();echo "New records created successfully";$stmt -> close();$mysqli -> close(); ?>

    Definition and Usage

    The prepare() / mysqli_prepare() function is used to prepare an SQL statement for execution.

    Syntax

    Object oriented style:

    $mysqli -> prepare(query)

    Procedural style:

    mysqli_prepare(connection, query)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    queryRequired. Specifies an SQL query. Note: Do not add semicolon to the end of the query!

    Technical Details

    Return Value: A statement object on success. FALSE on failure
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Perform query against a database: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Perform query if ($result = $mysqli -> query("SELECT * FROM Persons")) { echo "Returned rows are: " . $result -> num_rows; // Free result set $result -> free_result();}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The query() / mysqli_query() function performs a query against a database.

    Syntax

    Object oriented style:

    $mysqli -> query(query, resultmode)

    Procedural style:

    mysqli_query(connection, query, resultmode)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    queryRequired. Specifies the SQL query string
    resultmode Optional. A constant. Can be one of the following:
  • MYSQLI_USE_RESULT (Use this to retrieve large amount of data)
  • MYSQLI_STORE_RESULT (This is default)
  • Technical Details

    Return Value: For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.3.0 added the ability for async queries

    Example - Procedural style

    Perform query against a database: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }// Perform query if ($result = mysqli_query($con, "SELECT * FROM Persons")) { echo "Returned rows are: " . mysqli_num_rows($result); // Free result set mysqli_free_result($result);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Open a new connection to the MySQL server, with extra connect options: <?php$mysqli = mysqli_init();if (!$mysqli) { die("mysqli_init failed");} // Specify connection timeout$con -> options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);// Specify read options from named file instead of my.cnf$con -> options(MYSQLI_READ_DEFAULT_FILE, "myfile.cnf");$con -> real_connect("localhost","my_user","my_password","my_db");?> Look at example of procedural style at the bottom.

    Definition and Usage

    The real_connect() / mysqli_real_connect() function opens a new connection to the MySQL server. This function differs from connect() in the following ways:
  • real_connect() requires a valid object created by init()
  • real_connect() can be used with options() to set different options for the connection
  • real_connect() has a flag parameter
  • Syntax

    Object oriented style:

    $mysqli -> real_connect(host, username, password, dbname, port, socket, flag)

    Procedural style:

    mysqli_real_connect(connection, host, username, password, dbname, port, socket, flag)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    hostOptional. Specifies a host name or an IP address
    usernameOptional. Specifies the MySQL username
    passwordOptional. Specifies the MySQL password
    dbnameOptional. Specifies the default database to be used
    portOptional. Specifies the port number to attempt to connect to the MySQL server
    socketOptional. Specifies the socket or named pipe to be used
    flagOptional. Specifies different connection options. Possible values:
  • MYSQLI_CLIENT_COMPRESS - Use compression protocol
  • MYSQLI_CLIENT_FOUND_ROWS - Return number of matched rows (not affected rows)
  • MYSQLI_CLIENT_IGNORE_SPACE - Allow spaces after function names. Make function names reserved words
  • MYSQLI_CLIENT_INTERACTIVE - Allow interactive_timeout seconds of inactivity before closing connection
  • MYSQLI_CLIENT_SSL - Use SSL encryption
  • MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.6: Added MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag

    Example - Procedural style

    Open a new connection to the MySQL server, with extra connect options: <?php$con = mysqli_init();if (!$con) { die("mysqli_init failed");} // Specify connection timeoutmysqli_options($con, MYSQLI_OPT_CONNECT_TIMEOUT, 10);// Specify read options from named file instead of my.cnf mysqli_options($con, MYSQLI_READ_DEFAULT_FILE, "myfile.cnf"); mysqli_real_connect($con,"localhost","my_user","my_password","my_db");?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Escape special characters in strings: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Escape special characters, if any$firstname = $mysqli -> real_escape_string($_POST['firstname']); $lastname = $mysqli -> real_escape_string($_POST['lastname']);$age = $mysqli -> real_escape_string($_POST['age']);$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')"; if (!$mysqli -> query($sql)) { printf("%d Row inserted.\n", $mysqli->affected_rows);} $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement. Assume we have the following code: <?php $lastname = "D'Ore";$sql="INSERT INTO Persons (LastName) VALUES ('$lastname')"; // This query will fail, cause we didn't escape $lastnameif (!$mysqli -> query($sql)) { printf("%d Row inserted.\n", $mysqli->affected_rows);} ?>

    Syntax

    Object oriented style:

    $mysqli -> real_escape_string(escapestring)

    Procedural style:

    mysqli_real_escape_string(connection, escapestring)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    escapestringRequired. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

    Technical Details

    Return Value: Returns the escaped string
    PHP Version: 5+

    Example - Procedural style

    Escape special characters in strings: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Escape special characters, if any$firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']);$age = mysqli_real_escape_string($con, $_POST['age']);$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";if (!mysqli_query($con, $sql)) { printf("%d Row inserted.\n", mysqli_affected_rows($con));}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Execute a single SQL query. Store the result with store_result(): <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$mysqli -> real_query("SELECT * FROM Persons"); if ($mysqli -> field_count) { $result = $mysqli -> store_result(); $row = $result -> fetch_row(); // Free result set $result -> free_result();}$mysqli -> close(); ?>

    Definition and Usage

    The real_query() / mysqli_real_query() function executes a single SQL query. The result can be retrieved or stored with the store_result() or use_result() functions.

    Syntax

    Object oriented style:

    $mysqli -> real_query(query)

    Procedural style:

    mysqli_real_query(connection, query)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    queryRequired. The query to be executed

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Definition and Usage

    The reap_async_query() / mysqli_reap_async_query() function returns result from an async SQL query.

    Syntax

    Object oriented style:

    $mysqli -> reap_async_query()

    Procedural style:

    mysqli_reap_async_query(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: mysqli_result on success. FALSE on failure
    PHP Version: 5.3+
    PHP MySQLi Reference PHP mysqli Reference

    Definition and Usage

    The refresh() / mysqli_refresh() function refreshes/flushes tables or caches, or resets the replication server information.

    Syntax

    Object oriented style:

    $mysqli -> refresh(options)

    Procedural style:

    mysqli_refresh(connection, options)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    optionsThe options to refresh. Can be one of more of the following (separated by OR):
  • MYSQLI_REFRESH_GRANT - Refreshes the grant tables
  • MYSQLI_REFRESH_LOG - Flushes the logs
  • MYSQLI_REFRESH_TABLES - Flushes the table cache
  • MYSQLI_REFRESH_HOSTS - Flushes the host cache
  • MYSQLI_REFRESH_STATUS - Resets the status variables
  • MYSQLI_REFRESH_THREADS - Flushes the thread cache
  • MYSQLI_REFRESH_SLAVE - Resets the master server info, and restarts the slave
  • MYSQLI_REFRESH_MASTER - Removes the binary log files in the binary log index, and truncates the index file
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5.3+
    PHP mysqli Reference PHP mysqli Reference

    Example - Object Oriented style

    Turn off auto-committing, make some queries, commit the queries, then roll back the current transaction: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Turn autocommit off$mysqli -> autocommit(FALSE); // Insert some values $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); $mysqli -> query("INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli -> commit()) { echo "Commit transaction failed"; exit();}// Rollback transaction $mysqli -> rollback();$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The rollback() / mysqli_rollback() function rolls back the current transaction for the specified database connection. Tip: Also look at the commit() function, which commits the current transaction, and the autocommit() function, which turns on or off auto-committing database modifications.

    Syntax

    Object oriented style:

    $mysqli -> rollback(flags, name)

    Procedural style:

    mysqli_rollback(connection, flags, name)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    flagsOptional. A constant:
  • MYSQLI_TRANS_COR_AND_CHAIN - Appends "AND CHAIN"
  • MYSQLI_TRANS_COR_AND_NO_CHAIN - Appends "AND NO CHAIN"
  • MYSQLI_TRANS_COR_RELEASE - Appends "RELEASE"
  • MYSQLI_TRANS_COR_NO_RELEASE - Appends "NO RELEASE"
  • nameOptional. ROLLBACK/*name*/ is executed if this parameter is specified

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP Changelog: PHP 5.5: Added the flags and name parameters

    Example - Procedural style

    Turn off auto-committing, make some queries, commit the queries, then roll back the current transaction: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }// Turn autocommit offmysqli_autocommit($con,FALSE); // Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); // Commit transactionif (!$mysqli_commit($con)) { echo "Commit transaction failed"; exit();}// Rollback transactionmysqli_rollback($con);// Close connection mysqli_close($con);?> PHP mysqli Reference PHP MySQLi Reference

    Example - Object Oriented style

    Change the default database for the connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Return name of current default databaseif ($result = $mysqli -> query("SELECT DATABASE()")) { $row = $result -> fetch_row(); echo "Default database is " . $row[0]; $result -> close();}// Change db to "test" db$mysqli -> select_db("test");// Return name of current default databaseif ($result = $mysqli -> query("SELECT DATABASE()")) { $row = $result -> fetch_row(); echo "Default database is " . $row[0]; $result -> close();}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The select_db() / mysqli_select_db() function is used to change the default database for the connection.

    Syntax

    Object oriented style:

    $mysqli -> select_db(name)

    Procedural style:

    mysqli_select_db(connection, name)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    nameRequired. Specifies the database name

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    Example - Procedural style

    Change the default database for the connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }// Return name of current default databaseif ($result = mysqli_query($con, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); echo "Default database is " . $row[0]; mysqli_free_result($result);}// Change db to "test" dbmysqli_select_db($con, "test");// Return name of current default database if ($result = mysqli_query($con, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); echo "Default database is " . $row[0]; mysqli_free_result($result);}// Close connection mysqli_close($con);?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Change the default client character set: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo "Initial character set is: " . $mysqli -> character_set_name();// Change character set to utf8$mysqli -> set_charset("utf8"); echo "Current character set is: " . $mysqli -> character_set_name();$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The set_charset() / mysqli_set_charset() function specifies the default character set to be used when sending data to and from the database server. Note: For this function to work on a Windows platform, you need MySQL client library 4.1.11 or above (for MySQL 5.0, you need 5.0.6 or above).

    Syntax

    Object oriented style:

    $mysqli -> set_charset(charset)

    Procedural style:

    mysqli_set_charset(connection, charset)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    charsetRequired. Specifies the default character set

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5.0.5+

    Example - Procedural style

    Change the default client character set: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }echo "Initial character set is: " . mysqli_character_set_name($con);// Change character set to utf8 mysqli_set_charset($con,"utf8");echo "Current character set is: " . mysqli_character_set_name($con);mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Definition and Usage

    The set_local_infile_handler() / mysqli_set_local_infile_handler() function sets a callback function for LOAD DATA LOCAL INFILE command. The callback functions tasks are to read input from the file specified in LOAD DATA LOCAL INFILE, and to reformat it into the format understood by LOAD DATA INFILE. The returned data must match the format specified in the LOAD DATA.

    Syntax

    Object oriented style:

    $mysqli -> set_local_infile_handler(read_file)

    Procedural style:

    mysqli_set_local_infile_handler(read_file)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    read_funcRequired. Specifies a callback function or objext that can take the following params:stream - A PHP stream associated with the SQL commands INFILE&buffer - A string buffer to store the rewritten input into buflen - The maximum number of characters to be stored in the buffer&erromsg - If an error occurs you can store an error message in here

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+
    PHP MySQLi Reference PHP mysqli Reference

    Example - Object Oriented style

    Return the SQLSTATE error code for the last error: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Table Persons already exists, so we should get an error $sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)"if (!$mysqli -> query($sql)) { echo "SQLSTATE error: ". $mysqli -> sqlstate;} $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The sqlstate / mysqli_sqlstate() function returns the SQLSTATE error code for the last error. The error code consists of five characters. "00000" indicates no error. The values are specified by ANSI SQL and ODBC.

    Syntax

    Object oriented style:

    $mysqli -> sqlstate

    Procedural style:

    mysqli_sqlstate(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: A string containing the SQLSTATE error code for the last error
    PHP Version: 5+

    Example - Procedural state

    Return the SQLSTATE error code for the last error: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }// Table Persons already exists, so we should get an error $sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)"if (!mysqli_query($con, $sql)) { echo "SQLSTATE error: ". mysqli_sqlstate($con);} // Close connection mysqli_close($con);?> PHP mysqli Reference PHP MySQLi Reference

    Example - Object Oriented style

    Create an SSL connection: <?php$mysqli = mysqli_init();if (!$mysqli) { die("mysqli_init failed");} $mysqli -> ssl_set("key.pem", "cert.pem", "cacert.pem", NULL, NULL); if (!$mysqli -> real_connect("localhost","my_user","my_password","my_db")) { die("Connect Error: " . mysqli_connect_error());} // Some queries... $mysqli -> close();?> Look at example of procedural style at the bottom.

    Definition and Usage

    The ssl_set() / mysqli_ssl_set() function is used to establish secure connections using SSL. However, this function does nothing unless OpenSSL support is enabled. Note: This function must be called before real_connect(). Note: MySQL Native Driver does not support SSL before PHP 5.3.3. MySQL Native Driver is enabled by default on Microsoft Windows from PHP 5.3+.

    Syntax

    Object oriented style:

    $mysqli -> ssl_set(key, cert, ca, capath, cipher)

    Procedural style:

    mysqli_ssl_set(connection, key, cert, ca, capath, cipher)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use
    keyRequired. Specifies the path name to the key file
    certRequired. Specifies the path name to the certificate file
    caRequired. Specifies the path name to the certificate authority file
    capathRequired. Specifies the pathname to a directory that contains trusted SSL CA certificates in PEM format
    cipherRequired. Specifies a list of allowable ciphers to use for SSL encryption

    Technical Details

    Return Value: Always TRUE. If SSL setup is incorrect, real_connect() will return an error when you try to connect
    PHP Version: 5+

    Example - Procedural style

    Create an SSL connection: <?php $con = mysqli_init();if (!$con) { die("mysqli_init failed");} mysqli_ssl_set($con, "key.pem", "cert.pem", "cacert.pem", NULL, NULL); if (!mysqli_real_connect($con, "localhost", "my_user", "my_password", "my_db")) { die("Connect Error: " . mysqli_connect_error());} // Some queries... mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the current system status: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }echo "System status: ". $mysqli -> stat(); $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The stat() / mysqli_stat() function returns the current system status.

    Syntax

    Object oriented style:

    $mysqli -> stat()

    Procedural style:

    mysqli_stat(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: A string that describes the server status. FALSE on error
    PHP Version: 5+

    Example - Procedural style

    Return the current system status: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }echo "System status: ". mysqli_stat($con); mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Initialize a statement and return an object to use with stmt_prepare(): <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$city="Sandnes";// Create a prepared statement $stmt = $mysqli -> stmt_init();if ($stmt -> prepare("SELECT District FROM City WHERE Name=?")) { // Bind parameters $stmt -> bind_param("s", $city); // Execute query $stmt -> execute(); // Bind result variables $stmt -> bind_result($district); // Fetch value $stmt -> fetch(); printf("%s is in district %s", $city, $district); // Close statement $stmt -> close();} $mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The stmt_init() / mysqli_stmt_init() function initializes a statement and returns an object suitable for mysqli_stmt_prepare().

    Syntax

    Object oriented style:

    $mysqli -> stmt_init()

    Procedural style:

    mysqli_stmt_init(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an object
    PHP Version: 5+

    Example - Procedural style

    Initialize a statement and return an object to use with mysqli_stmt_prepare(): <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit; }$city="Sandnes";// Create a prepared statement $stmt = mysqli_stmt_init($con);if (mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?")) { // Bind parameters mysqli_stmt_bind_param($stmt, "s", $city); // Execute query mysqli_stmt_execute($stmt); // Bind result variables mysqli_stmt_bind_result($stmt, $district); // Fetch value mysqli_stmt_fetch($stmt); printf("%s is in district %s", $city, $district); // Close statement mysqli_stmt_close($stmt);} mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the thread ID for the current connection, then kill the connection: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }// Get thread id$thread_id = $mysqli -> thread_id;// Kill connection $mysqli -> kill($thread_id);?> Look at example of procedural style at the bottom.

    Definition and Usage

    The thread_id() / mysqli_thread_id() function returns the thread ID for the current connection. The connection can then be killed with the kill() function. Note: If the connection is broken and you reconnect, the thread ID will be changed. Therefore; get the thread ID only when you need it.

    Syntax

    Object oriented style:

    $mysqli -> thread_id()

    Procedural style:

    mysqli_thread_id(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns the thread ID for the current connection
    PHP Version: 5+

    Example - Procedural style

    Return the thread ID for the current connection, then kill the connection: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit;}// Get thread id$thread_id = mysqli_thread_id($con);// Kill connectionmysqli_kill($con, $thread_id);?> PHP MySQLi Reference PHP MySQLi Reference

    Definition and Usage

    The mysqli_thread_safe() function returns whether the client library is compiled as thread-safe.

    Syntax

    mysqli_thread_safe()

    Technical Details

    Return Value: TRUE if the client library is thread-safe. FALSE otherwise
    PHP Version: 5+
    PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Initiates the retrieval of a result-set from the last query executed: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif ($mysqli -> multi_query($sql)) { do { // Store first result set if ($result = $mysqli -> use_result()) { while ($row = $result -> fetch_row()) { printf("%s\n", $row[0]); } $result -> close(); } // if there are more result-sets, the print a divider if ($mysqli -> more_results()) { printf("-------------\n"); } //Prepare next result set } while ($mysqli -> next_result());}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The use_result() / mysqli_use_result() function initiates the retrieval of a result-set from the last query executed.

    Syntax

    Object oriented style:

    $mysqli -> use_result()

    Procedural style:

    mysqli_use_result(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: Returns an unbuffered result object. FALSE on error
    PHP Version: 5+

    Example - Procedural style

    Initiates the retrieval of a result-set from the last query executed: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers";// Execute multi queryif (mysqli_multi_query($con, $sql)) { do { // Store first result set if ($result = mysqli_use_result($con)) { while ($row = mysqli_fetch_row($result)) { printf("%s\n", $row[0]); } mysqli_free_result($result); } // if there are more result-sets, the print a divider if (mysqli_more_results($con)) { printf("-------------\n"); } //Prepare next result set } while (mysqli_next_result($con));}mysqli_close($con); ?> PHP MySQLi Reference PHP MySQLi Reference

    Example - Object Oriented style

    Return the number of warnings from the last query: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connectionif ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); }$mysqli -> query("CREATE TABLE myPersons LIKE Persons");$sql = "INSERT INTO myPersons (FirstName) VALUES( 'Hdghfhjgjtjyjn.,,øæløjkghfjbmbngfgffdhfhjgjgkjhlkhlkjljljlkjkljlkjkljkljlkj')"; $mysqli -> query($sql);if ($mysqli -> warning_count) { if ($result = $mysqli -> query("SHOW WARNINGS")) { $row = $result -> fetch_row(); printf("%s (%d): %s\n", $row[0], $row[1], $row[2]); $result -> close(); }}$mysqli -> close(); ?> Look at example of procedural style at the bottom.

    Definition and Usage

    The warning_count / mysqli_warning_count() function returns the number of warnings from the last query.

    Syntax

    Object oriented style:

    $mysqli -> warning_count

    Procedural style:

    mysqli_warning_count(connection)

    Parameter Values

    ParameterDescription
    connectionRequired. Specifies the MySQL connection to use

    Technical Details

    Return Value: The number of warnings from the last query. 0 if no warnings
    PHP Version: 5+

    Example - Procedural style

    Return the number of warnings from the last query: <?php $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); }mysqli_query($con, "CREATE TABLE myPersons LIKE Persons");$sql = "INSERT INTO myPersons (FirstName) VALUES('Hdghfhjgjtjyjn.,,øæløjkghfjbmbngfgffdhfhjgjgkjhlkhlkjljljlkjkljlkjkljkljlkj')"; mysqli_query($con, $sql);if (mysqli_warning_count($con)) { if ($result = mysqli_query($con, "SHOW WARNINGS")) { $row = mysql_fetch_row($result); printf("%s (%d): %s\n", $row[0], $row[1], $row[2]); mysqli_free_result($result); }} mysqli_close($con); ?> PHP MySQLi Reference

    Network Introduction

    The Network functions contains various network function and let you manipulate information sent to the browser by the Web server, before any other output has been sent.

    Installation

    The Network functions are part of the PHP core. There is no installation needed to use these functions.

    Network Functions

    FunctionDescription
    checkdnsrr()Checks DNS records for type corresponding to host
    closelog()Closes the connection of system logger
    define_syslog_variables()Deprecated and removed in PHP 5.4. Initializes the variables used in syslog functions
    dns_check_record()Alias of checkdnsrr()
    dns_get_mx()Alias of getmxrr()
    dns_get_record()Gets the DNS resource records associated with the specified hostname
    fsockopen()Opens an Internet or Unix domain socket connection
    gethostbyaddr()Returns the domain name for a given IP address
    gethostbyname()Returns the IPv4 address for a given domain/host name
    gethostbynamel()Returns a list of IPv4 address for a given domain/host name
    gethostname()Returns the host name
    getmxrr()Returns the MX records for the specified internet host name
    getprotobyname()Returns the protocol number for a given protocol name
    getprotobynumber() Returns the protocol name for a given protocol number
    getservbyname()Returns the port number for a given Internet service and protocol
    getservbyport()Returns the Internet service for a given port and protocol
    header_register_callback()Calls a header function
    header_remove()Removes an HTTP header previously set with the header() function
    header()Sends a raw HTTP header to a client
    headers_list()Returns a list of response headers to be sent to the browser
    headers_sent()Checks if/where headers have been sent
    http_response_code()Sets or returns the HTTP response status code
    inet_ntop()Converts a 32bit IPv4 or 128bit IPv6 address into a readable format
    inet_pton()Converts a readable IP address into a packed 32bit IPv4 or 128bit IPv6 format
    ip2long()Converts an IPv4 address into a long integer
    long2ip()Converts a long integer address into a string in IPv4 format
    openlog()Opens the connection of system logger
    pfsockopen()Opens a persistent Internet or Unix domain socket connection
    setcookie()Defines a cookie to be sent along with the rest of the HTTP headers
    setrawcookie()Defines a cookie (without URL encoding) to be sent along with the rest of the HTTP headers
    socket_get_status()Alias of stream_get_meta_data()
    socket_set_blocking()Alias of stream_set_blocking()
    socket_set_timeout()Alias of stream_set_timeout()
    syslog()Generates a system log message
    PHP Network Reference

    Example

    Check DNS records: <?php $domain="w3schools.com";if(checkdnsrr($domain,"MX")) { echo "Passed";} else { echo "Failed";}?>

    Definition and Usage

    The checkdnsrr() function checks DNS records for type corresponding to host. We can use the checkdnsrr() function to check our DNS record to verify the existence of a domain name or not.

    Syntax

    checkdnsrr(host, type)

    Parameter Values

    ParameterDescription
    hostRequired. Specifies an IP address or host name to check
    typeOptional. Specifies the type. Can be one of the following:
  • A
  • MX (default)
  • NS
  • SOA
  • PTR
  • CNAME
  • AAAA
  • A6
  • SRV
  • NAPTR
  • TXT
  • ANY
  • Technical Details

    Return Value: TRUE if any records are found, FALSE otherwise
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3: Now available on Windows platformsPHP 5.2.4: Added the TXT value of type
    PHP Network Reference PHP Network Reference

    Example

    Open and close connection of system logger: <?php function _log($text) {openlog("phperrors", LOG_PID | LOG_PERROR); syslog(LOG_ERR, $text);closelog();........}?>

    Definition and Usage

    The closelog() function closes the connection of system logger.

    Syntax

    closelog()

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    Check DNS records: <?php $domain="w3schools.com";if(dns_check_record($domain,"MX")) { echo "Passed";} else { echo "Failed";}?>

    Definition and Usage

    The dns_check_record() function is an alias of the checkdnsrr() function.

    Syntax

    dns_check_record(host, type)

    Parameter Values

    ParameterDescription
    hostRequired. Specifies an IP address or host name to check
    typeOptional. Specifies the type. Can be one of the following:
  • A
  • MX (default)
  • NS
  • SOA
  • PTR
  • CNAME
  • AAAA
  • A6
  • SRV
  • NAPTR
  • TXT
  • ANY
  • Technical Details

    Return Value: TRUE if any records are found, FALSE otherwise
    PHP Version: 5.0+
    PHP Network Reference PHP Network Reference

    Example

    Return details of mail exchanger records (MX records): <?php $domain="w3schools.com";if(dns_get_mx($domain,$mx_details)){ foreach($mx_details as $key=>$value){ echo "$key => $value <br>"; }}?>

    Definition and Usage

    The dns_get_mx() function is an alias of the getmxrr() function.

    Syntax

    dns_get_mx(host, mxhosts, weight)

    Parameter Values

    ParameterDescription
    hostRequired. Specifies the host name
    mxhostsRequired. An array that specifies a list of MX records found
    weightOptional. An array that specifies the weight information gathered

    Technical Details

    Return Value: TRUE if any records are found, FALSE otherwise
    PHP Version: 5.0+
    PHP Network Reference PHP Network Reference

    Example

    Gets the MX resource records associated with "www.w3schools.com": <?php print_r(dns_get_record("w3schools.com", DNS_MX));?>

    Definition and Usage

    The dns_get_record() function gets the DNS resource records associated with the specified hostname.

    Syntax

    dns_get_record(hostname, type, authns, addtl, raw)

    Parameter Values

    ParameterDescription
    hostnameRequired. Specifies a hostname (like "www.w3schools.com")
    typeOptional. Specifies the resource record type to search for. Can be one of the following:
  • DNS_A
  • DNS_CNAME
  • DNS_HINFO
  • DNS_CAA
  • DNS_MX
  • DNS_NS
  • DNS_PTR
  • DNS_SOA
  • DNS_TXT
  • DNS_AAAA
  • DNS_SRV
  • DNS_NAPTR
  • DNS_A6
  • DNS_ALL
  • DNS_ANY (default)
  • authnsOptional. Passed by reference and, if set, it will be populated with Resource Records for the Authoritative Name Servers
    addtlOptional. Passed by reference and, if set, it will be populated with any Additional Records
    rawOptional. A Boolean value. If set to TRUE, it queries only the requested type instead of looping type-by-type before getting the info stuff. Default is FALSE

    Technical Details

    Return Value: An array of associative arrays, FALSE on failure. Each array contains the following keys (at minimum):
  • host - The hostname
  • class - Always return IN (because this function only returns Internet class records)
  • type - The record type
  • ttl - "Time To Live" remaining for this record (original ttl minus the length of time passed since the server was queried)
  • Other keys in the arrays depends on the type parameter.
    PHP Version: 5.0+
    PHP Changelog: PHP 7.0.16: Added support for DNS_CAA type.PHP 5.4: Added the raw parameter.PHP 5.3: Available on Windows platforms.
    PHP Network Reference PHP Network Reference

    Example

    fsockopen() example: <?php $fp = fsockopen("www.w3schools.com", 80, $errno, $errstr, 20);if (!$fp) { echo "$errstr ($errno)<br>";} else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.w3schools.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp);}?>

    Definition and Usage

    The fsockopen() function opens an Internet or Unix domain socket connection.

    Syntax

    fsockopen(hostname, port, errno, errstr, timeout)

    Parameter Values

    ParameterDescription
    hostnameRequired. Specifies a hostname (like "www.w3schools.com"). ssl:// or tls:// works over TCP/IP to connect to the remote host
    portOptional. Specifies the port number. Use -1 for transports that do not use ports, like unix://
    errnoOptional. Specifies the system level error number
    errstrOptional. Specifies the error message as a string
    timeoutOptional. Specifies the connection timeout (in seconds)

    Technical Details

    Return Value: A file pointer that can be used with other file functions (such as fgets(), fwrite(), fclose()). FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A simple gethostbyaddr() example: <?php $host = gethostbyaddr($_SERVER["REMOTE_ADDR"]);echo $host;?>

    Definition and Usage

    The gethostbyaddr() function returns the domain name for a given IP address.

    Syntax

    gethostbyaddr(ipaddress)

    Parameter Values

    ParameterDescription
    ipaddressRequired. Specifies an IP address

    Technical Details

    Return Value: The host name on success. The IP address or FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A gethostbyname() example: <?php $ip = gethostbyname("www.w3schools.com");echo $ip;?>

    Definition and Usage

    The gethostbyname() function returns the IPv4 address for a given domain/host name.

    Syntax

    gethostbyname(hostname)

    Parameter Values

    ParameterDescription
    hostnameRequired. Specifies a hostname (like "www.w3schools.com")

    Technical Details

    Return Value: The IPv4 address on success. The hostname on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A gethostbynamel() example: <?php $hostlist = gethostbynamel("www.w3schools.com");print_r($hostlist);?>

    Definition and Usage

    The gethostbynamel() function returns a list of IPv4 address for a given domain/host name.

    Syntax

    gethostbynamel(hostname)

    Parameter Values

    ParameterDescription
    hostnameRequired. Specifies a hostname (like "www.w3schools.com")

    Technical Details

    Return Value: An array of IPv4 address on success. FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A gethostname() example: <?php echo gethostname;?>

    Definition and Usage

    The gethostname() function returns the host name for the local machine.

    Syntax

    gethostname()

    Technical Details

    Return Value: The host name on success. FALSE on failure
    PHP Version: 5.3+
    PHP Network Reference PHP Network Reference

    Example

    Return details of mail exchanger records (MX records): <?php $domain="w3schools.com";if(getmxrr($domain,$mx_details)){ foreach($mx_details as $key=>$value){ echo "$key => $value <br>"; }}?>

    Definition and Usage

    The getmxrr() function returns the MX records for the specified internet host name.

    Syntax

    getmxrr(host, mxhosts, weight)

    Parameter Values

    ParameterDescription
    hostRequired. Specifies the host name
    mxhostsRequired. An array that specifies a list of MX records found
    weightOptional. An array that specifies the weight information gathered

    Technical Details

    Return Value: TRUE if any records are found, FALSE otherwise
    PHP Version: 4.0+
    PHP Changelog: PHP 5.3: Now available on Windows platforms
    PHP Network Reference PHP Network Reference

    Example

    A getprotobyname() example: <?php $protocolnum = getprotobyname("tcp");echo $protocolnum;?>

    Definition and Usage

    The getprotobyname() function returns the protocol number for a given protocol name.

    Syntax

    getprotobyname(protocolname)

    Parameter Values

    ParameterDescription
    protocolnameRequired. Specifies a protocol name (like "tcp")

    Technical Details

    Return Value: The protocol number on success. FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A getprotobynumber() example: <?php $protocolname = getprotobynumber(6);echo $protocolname;?>

    Definition and Usage

    The getprotobynumber() function returns the protocol name for a given protocol number.

    Syntax

    getprotobynumber(protocolnumber)

    Parameter Values

    ParameterDescription
    protocolnumberRequired. Specifies a protocol number (like 17)

    Technical Details

    Return Value: The protocol name on success. FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A getservbyname() example: <?php $portnum = getservbyname("http", "tcp");echo $portnum;?>

    Definition and Usage

    The getservbyname() function returns the port number for a given Internet service and protocol.

    Syntax

    getservbyname(service, protocol)

    Parameter Values

    ParameterDescription
    serviceRequired. Specifies the Internet service name (like "http")
    protocolRequired. Specifies a protocol name (like "tcp" or "udp")

    Technical Details

    Return Value: The port number on success. FALSE on failure
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A getservbyport() example: <?php $intservname = getservbyport(80, "tcp");echo $intservname;?>

    Definition and Usage

    The getservbyport() function returns the Internet service for a given port and protocol.

    Syntax

    getservbyport(port, protocol)

    Parameter Values

    ParameterDescription
    portRequired. Specifies the port number (like 80)
    protocolRequired. Specifies a protocol name (like "tcp" or "udp")

    Technical Details

    Return Value: The Internet Service name on success
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    A getservbyname() example: <?php $portnum = getservbyname("http", "tcp");echo $portnum;?>

    Definition and Usage

    The header_register_callback() function calls a header function (will be executed after PHP has prepared all headers to be sent, and before any other output is sent).

    Syntax

    header_register_callback(callback)

    Parameter Values

    ParameterDescription
    callbackRequired. Specifies a callback function

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5.4+
    PHP Network Reference PHP Network Reference

    Example

    Remove specific header: <?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache"); header("Pragma: no-cache");header_remove("Pragma"); ?>

    Definition and Usage

    The header_remove() function removes an HTTP header previously set with the header() function.

    Syntax

    header_remove(headername)

    Parameter Values

    ParameterDescription
    headernameOptional. Specifies a header name to be removed. If omitted, all previously set headers are removed

    Technical Details

    Return Value: Nothing
    PHP Version: 5.3+

    More Examples

    Example

    Remove all previously set headers: <?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache"); header("Pragma: no-cache");header_remove(); ?> PHP Network Reference PHP Network Reference

    Example

    Send three HTTP headers to prevent page caching: <?php // Date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache"); header("Pragma: no-cache"); ?> <html> <body> ... ... Note: There are options that users may set to change the browser's default caching settings. By sending the headers above, you will override any of those settings and force the browser to not cache!

    Definition and Usage

    The header() function sends a raw HTTP header to a client. It is important to notice that the header() function must be called before any actual output is sent!

    Syntax

    header(header, replace, http_response_code)

    Parameter Values

    ParameterDescription
    headerRequired. Specifies the header string to send
    replaceOptional. Indicates whether the header should replace a previous similar header or add a new header of the same type. Default is TRUE (will replace). FALSE allows multiple headers of the same type
    http_response_codeOptional. Forces the HTTP response code to the specified value

    Technical Details

    Return Value: Nothing
    PHP Version: 4.0+
    PHP Changelog: PHP 5.1.2: Now prevents that more than one header to be sent at once. This is a protection against header injection attacks

    More Examples

    Example

    Let the user be prompted to save a generated PDF file (Content-Disposition header is used to supply a recommended filename and force the browser to display the save dialog box): <?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?> <html> <body> ... ... PHP Network Reference PHP Network Reference

    Example

    Return a list of response headers sent: <?php setcookie("TestCookie","SomeValue"); header("X-Sample-Test: foo"); header("Content-type: text/plain"); ?> <html> <body> <?php var_dump(headers_list()); ?> </body> </html> The output of the code above could be: array(4) { [0]=> string(23) "X-Powered-By: PHP/7.1.1" [1]=> string(19) "Set-Cookie: TestCookie=SomeValue" [2]=> string(18) "X-Sample-Test: foo" [3]=> string(24) "Content-type: text/plain" }

    Definition and Usage

    The headers_list() function returns a list of response headers to be sent to the browser. Tip: To determine whether or not the headers have been sent yet, use the headers_sent() function.

    Syntax

    headers_list()

    Technical Details

    Return Value: A numerically indexed array of headers on success
    PHP Version: 5.0+
    PHP Network Reference PHP Network Reference

    Example

    If no headers are sent, send one: <?php if (!headers_sent()) { header("Location: https://www.w3schools.com/"); exit; } ?> <html> <body> ... ...

    Definition and Usage

    The headers_sent() function checks if/where headers have been sent.

    Syntax

    headers_sent(file,line)

    Parameter Values

    ParameterDescription
    fileOptional. If the file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables
    lineOptional. Specifies the line number where the output started

    Technical Details

    Return Value: TRUE if HTTP headers has been sent, FALSE otherwise
    PHP Version: 4.0+
    PHP Changelog: PHP 4.3: Added the optional file and line parameters

    More Examples

    Example

    Using the optional file and line parameters: <?php // $file and $line are passed in for later use // Do not assign them values beforehand if (!headers_sent($file, $line)) { header("Location: https://www.w3schools.com/"); exit; // Trigger an error here } else { echo "Headers sent in $file on line $line"; exit; } ?> <html> <body> ... ... PHP Network Reference PHP Network Reference

    Example

    Set the HTTP response status code to 404: <?php http_response_code(404);?>

    Definition and Usage

    The http_response_code() function sets or returns the HTTP response status code.

    Syntax

    http_response_code(code)

    Parameter Values

    ParameterDescription
    codeOptional. Specifies a response code (like 404)

    Technical Details

    Return Value: If code is set, the previous status code is returned. If code is not set, the current status code is returned
    PHP Version: 5.4+
    PHP Network Reference PHP Network Reference

    Example

    Convert a packed address into a readable format: <?php $addr = chr(127) . chr(0) . chr(1) . chr(1);$exp = inet_ntop($addr); echo $exp;?> Try it Yourself »

    Definition and Usage

    The inet_ntop() function converts a 32bit IPv4 or 128bit IPv6 address into a readable format.

    Syntax

    inet_ntop(address)

    Parameter Values

    ParameterDescription
    addressRequired. Specifies a 32bit IPv4 or 128bit IPv6 address

    Technical Details

    Return Value: A human readable address on success. FALSE on failure
    PHP Version: 5.1+
    PHP Changelog: PHP 5.3: Now available on Windows platforms
    PHP Network Reference PHP Network Reference

    Example

    Convert a readable IP address into a packed format: <?php $addr = inet_pton("127.0.1.1");echo $addr;?>

    Definition and Usage

    The inet_pton() function converts a readable IP address into a packed 32bit IPv4 or 128bit IPv6 format.

    Syntax

    inet_pton(address)

    Parameter Values

    ParameterDescription
    addressRequired. Specifies a readable IP address

    Technical Details

    Return Value: The address as a packed 32bit IPv4 or 128bit IPv6 format. FALSE on failure
    PHP Version: 5.1+
    PHP Changelog: PHP 5.3: Now available on Windows platforms
    PHP Network Reference PHP Network Reference

    Example

    Convert an IPv4 address into a long integer: <?php $ip = gethostbyname("www.w3schools.com");$out = "The following URLs are equivalent:<br>";$out .= "https://www.w3schools.com/, https://" . $ip . "/, and https://" . sprintf("%u", ip2long($ip)) . "/";echo $out;?>

    Definition and Usage

    The ip2long() function converts an IPv4 address into a long integer.

    Syntax

    ip2long(address)

    Parameter Values

    ParameterDescription
    addressRequired. Specifies a standard IP address

    Technical Details

    Return Value: A long integer. FALSE on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 5.5: Before this version, on Windows, this function might return a valid number even if the passed value was not an IPv4 address.PHP 5.2: PHP 5.5: Before this version, this function might return a valid number even if the passed value was not an IPv4 address.
    PHP Network Reference PHP Network Reference

    Example

    Convert a long integer address into a string in IPv4 format: <?php echo(long2ip(344294967296));?> Try it Yourself »

    Definition and Usage

    The long2ip() function converts a long integer address into a string in IPv4 format.

    Syntax

    long2ip(address)

    Parameter Values

    ParameterDescription
    addressRequired. Specifies a long integer that represents an IP address

    Technical Details

    Return Value: The IP address as a string
    PHP Version: 4.0+
    PHP Changelog: PHP 7.1: Changed the address parameter from string to integer.
    PHP Network Reference PHP Network Reference

    Example

    Open and close connection of system logger: <?php function _log($text) {openlog("phperrors", LOG_PID | LOG_PERROR); syslog(LOG_ERR, $text);closelog();........}?>

    Definition and Usage

    The openlog() function opens the connection of system logger.

    Syntax

    openlog(ident, option, facility)

    Parameter Values

    ParameterDescription
    identRequired. Specifies a string ident that is added to each message
    optionRequired. Specifies what logging options will be used when generating a log message. Can be one or more of the following options (separated with |):
  • LOG_CONS
  • LOG_NDELAY
  • LOG_ODELAY
  • LOG_PERROR
  • LOG_PID
  • facilityRequired. Specifies what type of program is logging the message:
  • LOG_AUTH
  • LOG_AUTHPRIV
  • LOG_CRON
  • LOG_DAEMON
  • LOG_KERN
  • LOG_LOCAL0...LOG_LOCAL7
  • LOG_LPR
  • LOG_MAIL
  • LOG_NEWS
  • LOG_SYSLOG
  • LOG_USER - (is the only valid log type for Windows OS)
  • LOG_UUCP
  • Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    pfsockopen() example: <?php $fp = pfsockopen("www.w3schools.com", 80, $errno, $errstr, 20);if (!$fp) { echo "$errstr ($errno)<br>";} else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.w3schools.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp);}?>

    Definition and Usage

    The pfsockopen() function opens a persistent Internet or Unix domain socket connection. Note: This function is almost identical to fsockopen(). The difference is that the connection is not closed after the script finishes. This function is the persistent version of fsockopen().

    Syntax

    pfsockopen(hostname, port, errno, errstr, timeout)

    Parameter Values

    ParameterDescription
    hostnameRequired. Specifies a hostname (like "www.w3schools.com"). ssl:// or tls:// works over TCP/IP to connect to the remote host
    portOptional. Specifies the port number. Use -1 for transports that do not use ports, like unix://
    errnoOptional. Specifies the system level error number
    errstrOptional. Specifies the error message as a string
    timeoutOptional. Specifies the connection timeout (in seconds)

    Technical Details

    Return Value: A file pointer that can be used with other file functions (such as fgets(), fwrite(), fclose()). FALSE on failure.
    PHP Version: 4.0+
    PHP Network Reference PHP Network Reference

    Example

    The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set: <!DOCTYPE html><?php$cookie_name = "user";$cookie_value = "John Doe";setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day?><html><body><?phpif(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!";} else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name];}?></body></html> Try it Yourself »

    Definition and Usage

    The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value. Note: The setcookie() function must appear BEFORE the <html> tag. Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

    Syntax

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

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the cookie
    valueOptional. Specifies the value of the cookie
    expireOptional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0
    pathOptional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in
    domainOptional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain
    secureOptional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE
    httponlyOptional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4+
    PHP Changelog: PHP 5.5 - A Max-Age attribute was included in the Set-Cookie header sent to the clientPHP 5.2 - The httponly parameter was added

    More Examples

    Example

    Several expire dates for cookies: <?php$value = "Hello world!";// cookie will expire when the browser closesetcookie("myCookie", $value);// cookie will expire in 1 hoursetcookie("myCookie", $value, time() + 3600);// cookie will expire in 1 hour, and will only be available// within the php directory + all sub-directories of phpsetcookie("myCookie", $value, time() + 3600, "/php/");?> <html><body>...some code... </body></html> Try it Yourself »

    Example

    To modify a cookie, just set (again) the cookie using the setcookie() function: <?php$cookie_name = "user";$cookie_value = "Alex Porter"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");?><html><body><?phpif(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!";} else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name];}?></body></html> Try it Yourself »

    Example

    To delete a cookie, use the setcookie() function with an expiration date in the past: <?php// set the expiration date to one hour agosetcookie("user", ", time() - 3600);?><html><body><?phpecho "Cookie 'user' is deleted.";?></body></html> Try it Yourself »

    Example

    Create a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable: <?phpsetcookie("test_cookie", "test", time() + 3600, '/');?> <html><body><?phpif(count($_COOKIE) > 0) { echo "Cookies are enabled.";} else { echo "Cookies are disabled.";}?> </body></html> Try it Yourself » PHP Network Reference PHP Network Reference

    Example

    The following example creates a cookie with PHP. The cookie is named "user" and the value will be "John Doe". The cookie value will not be URL encoded. The cookie will expire after 30 days (86400 * 30). Using "/", means that the cookie is available in entire website (otherwise, select the directory you prefer): <?php $cookie_name = "user";$cookie_value = "John"; setrawcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");// 86400 = 1 day?><html><body><?phpecho "Cookie is set."; ?></body></html>?> Try it Yourself »

    Definition and Usage

    The setrawcookie() function defines a cookie (without URL encoding) to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value. Note: The setrawcookie() function must appear BEFORE the <html> tag. Note: To automatically URL-encode the cookie value when sending, and automatically decode when receiving, use the setcookie() function instead.

    Syntax

    setrawcookie(name, value, expire, path, domain, secure);

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the cookie
    valueOptional. Specifies the value of the cookie
    expireOptional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is not set, the cookie will expire at the end of the session (when the browser closes)
    pathOptional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in
    domainOptional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to ".example.com". Setting it to www.example.com will make the cookie only available in the www subdomain
    secureOptional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE.

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5+

    More Examples

    Example

    Retrieve the value of the cookie named "user" (using the global variable $_COOKIE). Also use the isset() function to find out if the cookie exists: <html><body><?php$cookie_name = "user";if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' does not exist!";} else { echo "Cookie is named: " . $cookie_name . "<br>Value is: " . $_COOKIE[$cookie_name];}?></body></html> Try it Yourself »

    Example

    To modify a cookie, just set (again) the cookie using the setrawcookie() function: <?php$cookie_name = "user";$cookie_value = "Alex"; setrawcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");?><html><body><?php$cookie_name = "user";if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' does not exist!";} else { echo "Cookie is named: " . $cookie_name . "<br>Value is: " . $_COOKIE[$cookie_name];}?></body></html> Try it Yourself »

    Example

    To delete a cookie, use the setrawcookie() function with an expiration date in the past: <?php$cookie_name = "user"; unset($_COOKIE[$cookie_name]);// empty value and expiration one hour before$res = setrawcookie($cookie_name, '', time() - 3600);?><html><body><?phpecho "Cookie 'user' is deleted.";?></body></html> Try it Yourself »

    Example

    Create a small script that checks whether cookies are enabled. First, try to create a test cookie with the setrawcookie() function, then count the $_COOKIE array variable: <?phpsetrawcookie("test_cookie", "test", time() + 3600, '/');?> <html><body><?phpif(count($_COOKIE) > 0) { echo "Cookies are enabled";} else { echo "Cookies are disabled";}?> </body></html> Try it Yourself » PHP Network Reference PHP Network Reference

    Definition and Usage

    The socket_get_status() function is an alias of the stream_get_meta_data() function. PHP Network Reference PHP Network Reference

    Definition and Usage

    The socket_set_blocking() function is an alias of the stream_get_meta_data() function. PHP Network Reference PHP Network Reference

    Definition and Usage

    The socket_set_timeout() function is an alias of the stream_get_meta_data() function. PHP Network Reference PHP Network Reference

    Example

    Open and close connection of system logger: <?php function _log($text) {openlog("phperrors", LOG_PID | LOG_PERROR); syslog(LOG_ERR, $text);closelog();........}?>

    Definition and Usage

    The syslog() function generates a system log message.

    Syntax

    syslog(priority, message)

    Parameter Values

    ParameterDescription
    priorityRequired. Specifies ... Can be one of the following options:
  • LOG_EMERG
  • LOG_ALERT
  • LOG_CRIT
  • LOG_ERR
  • LOG_WARNING
  • LOG_NOTICE
  • LOG_INFO
  • LOG_DEBUG
  • messageRequired. Specifies the message to send

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    PHP Version: 4.0+
    PHP Network Reference

    SimpleXML Introduction

    SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout. SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays and objects.

    Installation

    From PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to use these functions.

    SimpleXML Functions

    FunctionDescription
    __construct()Creates a new SimpleXMLElement object
    __toString()Returns the string content of an element
    addAttribute()Appends an attribute to the SimpleXML element
    addChild()Appends a child element the SimpleXML element
    asXML()Returns a well-formed XML string (XML version 1.0) from a SimpleXML object
    attributes()Returns the attributes/values of an element
    children()Returns the children of a specified node
    count()Counts the children of a specified node
    getDocNamespaces()Returns the namespaces declared in document
    getName()Returns the name of an element
    getNamespaces()Returns the namespaces used in document
    registerXPathNamespace()Creates a namespace context for the next XPath query
    saveXML()Alias of asXML()
    simplexml_import_dom()Returns a SimpleXMLElement object from a DOM node
    simplexml_load_file()Converts an XML document to an object
    simplexml_load_string()Converts an XML string to an object
    xpath()Runs an XPath query on XML data

    SimpleXML Iteration Functions

    FunctionDescription
    current()Returns the current element
    getChildren()Returns the child elements of the current element
    hasChildren()Checks whether the current element has children
    key()Returns the XML tag name of the current element
    next()Moves to the next element
    rewind()Rewinds to the first element
    valid()Checks whether the current element is valid
    PHP SimpleXML Reference

    Example

    Create a SimpleXMLElement object from a string: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml=new SimpleXMLElement($note); echo $xml->asXML();?> Run Example »

    Definition and Usage

    The __construct() function creates a new SimpleXMLElement object.

    Syntax

    SimpleXMLElement::__construct(data, options, data_is_url, ns, is_prefix)

    Parameter Values

    ParameterDescription
    dataRequired. Specifies A well-formed XML string or the path or URL to an XML document if data_is_url is TRUE
    optionsOptional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
  • LIBXML_COMPACT - Activate nodes allocation optimization (may speed up application)
  • LIBXML_DTDATTR - Set default DTD attributes
  • LIBXML_DTDLOAD - Load external subset
  • LIBXML_DTDVALID - Validate with the DTD
  • LIBXML_NOBLANKS - Remove blank nodes
  • LIBXML_NOCDATA - Merge CDATA as text nodes
  • LIBXML_NOEMPTYTAG - Expand empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
  • LIBXML_NOENT - Substitute entities
  • LIBXML_NOERROR - Do not show error reports
  • LIBXML_NONET - Disable network access while loading documents
  • LIBXML_NOWARNING - Do not show warning reports
  • LIBXML_NOXMLDECL - Drop the XML declaration when saving a document
  • LIBXML_NSCLEAN - Remove redundant namespace declarations
  • LIBXML_PARSEHUGE - Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document and limits of the size of text nodes
  • LIBXML_XINCLUDE - Implement XInclude substitution
  • LIBXML_ERR_ERROR - Get recoverable errors
  • LIBXML_ERR_FATAL - Get fatal errors
  • LIBXML_ERR_NONE - Get no errors
  • LIBXML_ERR_WARNING - Get simple warnings
  • LIBXML_VERSION - Get libxml version (e.g. 20605 or 20617)
  • LIBXML_DOTTED_VERSION - Get dotted libxml version (e.g. 2.6.5 or 2.6.17)
  • data_is_urlOptional. TRUE specifies that data is a path/URL to an XML document instead of string data. Default is FALSE
    nsOptional. Specifies a namespace prefix or URI
    is_prefixOptional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE

    Technical Details

    Return Value: Returns a SimpleXMLElement object that represents data
    PHP Version: 5.0+
    PHP Changelog: PHP 5.2.0: Added the optional ns and is_prefix parameters.PHP 5.1.2: Added the optional options and data_is_url parameters.

    More Examples

    Assume we have the following XML file, "note.xml": <?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

    Example

    Create a SimpleXMLElement object from a URL: <?php$xml=new SimpleXMLElement("note.xml", 0, TRUE);echo $xml->asXML();?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return the string content of the <note> element: <?php$xml = new SimpleXMLElement("<note>Hello <to>Tove</to><from>Jani</from>World!</note>"); echo $xml;?> Run Example »

    Definition and Usage

    The __toString() function returns the string content of an element. This function returns the string content that is directly in the element - not the string content that is inside this element's children!

    Syntax

    SimpleXMLElement::__toString()

    Technical Details

    Return Value: The string content on success. An empty string on failure
    PHP Version: 5.3+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Add an attribute to the root element (<note>) and to the <body> element: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLElement($note);// Add attribute to root element$xml->addAttribute("type","private"); // Add attribute to body element $xml->body->addAttribute("date","2014-01-01"); echo $xml->asXML();?> Run Example »

    Definition and Usage

    The addAttribute() function appends an attribute to the SimpleXML element.

    Syntax

    SimpleXMLElement::addAttribute(name, value, ns)

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the attribute to add
    valueOptional. Specifies the value of the attribute
    nsOptional. Specifies a namespace for the attribute

    Technical Details

    Return Value: Nothing
    PHP Version: 5.1.3+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Add a child element to the <body> element and a new <footer> element: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLElement($note);// Add a child element to the body element$xml->body->addChild("date","2014-01-01");// Add a child element after the last element inside note $footer = $xml->addChild("footer","Some footer text");echo $xml->asXML();?> Run Example »

    Definition and Usage

    The addChild() function appends a child element to the SimpleXML element.

    Syntax

    SimpleXMLElement::addChild(name, value, ns)

    Parameter Values

    ParameterDescription
    nameRequired. Specifies the name of the child element to add
    valueOptional. Specifies the value of the child element
    nsOptional. Specifies a namespace for the child element

    Technical Details

    Return Value: A SimpleXMLElement object that represents the child added to the XML node
    PHP Version: 5.1.3+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return a well-formed XML string (XML version 1.0) from a SimpleXML object: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLElement($note);echo $xml->asXML();?> Run Example »

    Definition and Usage

    The asXML() function returns a well-formed XML string (XML version 1.0) from a SimpleXML object.

    Syntax

    SimpleXMLElement::asXML(filename)

    Parameter Values

    ParameterDescription
    filenameOptional. If specified, the data is written to the file, instead of returning a string

    Technical Details

    Return Value: A string (or TRUE if the filename parameter is set) on success. FALSE on failure
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return the attributes and values for the XML <body> element: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from> <heading>Reminder</heading><body date="2014-01-01" type="private">Do not forget me this weekend!</body></note>XML; $xml = simplexml_load_string($note);foreach($xml->body[0]->attributes() as $a => $b) { echo $a,'="',$b,"<br>"; }?> Run Example »

    Definition and Usage

    The attributes() function returns the attributes and values of an XML element.

    Syntax

    SimpleXMLElement::attributes(ns, prefix)

    Parameter Values

    ParameterDescription
    nsOptional. Specifies a namespace for the retrieved attributes
    prefixOptional. Specifies TRUE if ns is a prefix and FALSE if ns is a URI. Default is FALSE

    Technical Details

    Return Value: A SimpleXMLElement object on success
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Find the children of the note node: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from> <heading>Reminder</heading><body>Do not forget me this weekend!</body></note>XML; $xml=simplexml_load_string($note);foreach ($xml->children() as $child) { echo "Child node: " . $child . "<br>"; }?> Run Example »

    Definition and Usage

    The children() function finds the children of a specified node.

    Syntax

    SimpleXMLElement::children(ns, prefix)

    Parameter Values

    ParameterDescription
    nsOptional. Specifies an XML namespace
    prefixOptional. A Boolean value. If TRUE ns is regarded as a prefix. If FALSE ns is regarded as a namespace URL. Default is FALSE

    Technical Details

    Return Value: Returns a SimpleXMLElement object
    PHP Version: 5.0+
    PHP Changelog: PHP 5.2: Added the optional prefix parameter

    More Examples

    Example

    Find the children of the body node: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from> <heading>Reminder</heading><body><span>Important!</span> Do not forget me this weekend!</body></note>XML; $xml=simplexml_load_string($note);foreach ($xml->body[0]->children() as $child) { echo "Child node: " . $child . "<br>"; }?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Count the children of the <car> element: <?php$xml=<<<XML <cars> <car name="Volvo"> <child/> <child/> <child/> <child/> </car> <car name="BMW"> <child/> <child/> </car></cars>XML;$elem=new SimpleXMLElement($xml);foreach ($elem as $car) { printf("%s has %d children.<br>", $car['name'], $car->count()); }?> Run Example »

    Definition and Usage

    The count() function counts the children of a specified node.

    Syntax

    SimpleXMLElement::count();

    Technical Details

    Return Value: The number of child elements of an element
    PHP Version: 5.3+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return the namespaces declared in the root of the XML document: <?php$xml=<<<XML<?xml version="1.0" standalone="yes"?><cars xmlns:c="http://w3schools.com/ns"> <c:car id="1">Volvo</c:car> <c:car id="2">BMW</c:car> <c:car id="3">Saab</c:car> </cars>XML; $sxe=new SimpleXMLElement($xml);$ns=$sxe->getDocNamespaces(); print_r($ns);?> Run Example »

    Definition and Usage

    The getDocNamespaces() function returns the namespaces declared in an XML document.

    Syntax

    SimpleXMLElement::getDocNamespaces(recursive, from_root)

    Parameter Values

    ParameterDescription
    recursiveOptional. Specifies a Boolean value. If TRUE, all namespaces declared in document are returned. If FALSE, only namespaces declared in root node is returned. Default is FALSE
    from_rootOptional. Specifies a Boolean value. TRUE checks namespaces from the root of the XML document. FALSE checks namespaces under a child node. Default is TRUE

    Technical Details

    Return Value: An array of namespace names with their associated URIs
    PHP Version: 5.1.2+
    PHP Changelog: PHP 5.4: The from_root parameter was added

    More Examples

    Example

    Return all namespaces declared in the XML document: <?php$xml=<<<XML<?xml version="1.0" standalone="yes"?><cars xmlns:c="http://w3schools.com/ns"> <c:car id="1">Volvo</c:car> <c:car id="2">BMW</c:car> <c:car id="3" a:country="Sweden" xmlns:a="http://w3schools.com/country">Saab</c:car> </cars>XML; $sxe=new SimpleXMLElement($xml);$ns=$sxe->getDocNamespaces(TRUE); var_dump($ns);?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return the name of the XML element and the children: <?php$xml=<<<XML<?xml version="1.0" standalone="yes"?><cars> <car id="1">Volvo</car> <car id="2">BMW</car> <car id="3">Saab</car> </cars>XML;$sxe=new SimpleXMLElement($xml); // Get the name of the cars elementecho $sxe->getName() . "<br>"; // Also print out the names of the children of the cars elementforeach ($sxe->children() as $child) { echo $child->getName() . "<br>"; }?> Run Example »

    Definition and Usage

    The getName() function returns the name of the XML element.

    Syntax

    SimpleXMLElement::getName()

    Technical Details

    Return Value: The name of the XML element, as a string
    PHP Version: 5.1.3+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Return all the namespaces used in the XML document: <?php$xml=<<<XML<?xml version="1.0" standalone="yes"?><cars xmlns:c="http://w3schools.com/ns" xmlns:a="http://w3schools.com/country"> <c:car id="1">Volvo</c:car> <c:car id="2">BMW</c:car> <c:car id="3">Saab</c:car> </cars>XML;$sxe=new SimpleXMLElement($xml);$ns=$sxe->getNamespaces(true);var_dump($ns); ?> Run Example »

    Definition and Usage

    The getNamespaces() function returns the namespaces used in an XML document.

    Syntax

    SimpleXMLElement::getNamespaces(recursive)

    Parameter Values

    ParameterDescription
    recursiveOptional. Specifies a Boolean value. If TRUE, all namespaces used in document are returned. If FALSE, only namespaces used in root node is returned. Default is FALSE

    Technical Details

    Return Value: An array of namespace names with their associated URIs
    PHP Version: 5.1.2+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Create a namespace context for the next XPath query: <?php$xml=<<<XML<book xmlns:chap="http://example.org/chapter-title"> <title>My Book</title> <chapter id="1"> <chap:title>Chapter 1</chap:title> <para>Donec velit. Nullam eget tellus...</para> </chapter> <chapter id="2"> <chap:title>Chapter 2</chap:title> <para>Lorem ipsum dolor sit amet....</para> </chapter></book>XML; $sxe=new SimpleXMLElement($xml); $sxe->registerXPathNamespace('c','http://example.org/chapter-title'); $result=$sxe->xpath('//c:title');foreach ($result as $title) { echo $title . "<br>"; }?> Run Example »

    Definition and Usage

    The registerXPathNamespace() function creates a namespace context for the next XPath query. This function is useful if a namespace prefix is changed in an XML document. The registerXPathNamespace() function will create a prefix for specified namespace, so that the affected XML nodes can be accessed without altering the application code too much.

    Syntax

    SimpleXMLElement::registerXPathNamespace(prefix, ns)

    Parameter Values

    ParameterDescription
    prefixRequired. Specifies the namespace prefix to use in the XPath query for the namespace given in ns
    nsRequired. Specifies the namespace to use for the XPath query

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 5.1+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Definition and Usage

    The saveXML() function is an alias of the asXML() function. PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Take a node of a DOM document and make it into a SimpleXML node: <?php $dom=new domDocument; $dom->loadXML("<note><to>Tove</to><from>Jani</from></note>"); $x=simplexml_import_dom($dom);echo $x->from;?> Run Example »

    Definition and Usage

    The simplexml_import_dom() function returns a SimpleXMLElement object from a DOM node.

    Syntax

    simplexml_import_dom(node, classname)

    Parameter Values

    ParameterDescription
    nodeRequired. Specifies a DOM element node
    classnameOptional. Specifies the class of the new object

    Technical Details

    Return Value: A SimpleXMLElement object on success. FALSE on failure
    PHP Version: 5+

    More Examples

    Example

    Output the title of the second book node in the DOM document: <?php$dom=new domDocument; $dom->loadXML("<books><book><title>Title1</title></book><book><title>Title2</title></book></books>"); $x=simplexml_import_dom($dom);echo $x->book[1]->title;?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Convert an XML file into an object, then output keys and elements of the object: <?php $xml=simplexml_load_file("note.xml");print_r($xml);?> Run Example »

    Definition and Usage

    The simplexml_load_file() function converts an XML document to an object.

    Syntax

    simplexml_load_file(file, class, options, ns, is_prefix)

    Parameter Values

    ParameterDescription
    fileRequired. Specifies the path to the XML file
    classOptional. Specifies the class of the new object
    optionsOptional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
  • LIBXML_COMPACT - Activate nodes allocation optimization (may speed up application)
  • LIBXML_DTDATTR - Set default DTD attributes
  • LIBXML_DTDLOAD - Load external subset
  • LIBXML_DTDVALID - Validate with the DTD
  • LIBXML_NOBLANKS - Remove blank nodes
  • LIBXML_NOCDATA - Merge CDATA as text nodes
  • LIBXML_NOEMPTYTAG - Expand empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
  • LIBXML_NOENT - Substitute entities
  • LIBXML_NOERROR - Do not show error reports
  • LIBXML_NONET - Disable network access while loading documents
  • LIBXML_NOWARNING - Do not show warning reports
  • LIBXML_NOXMLDECL - Drop the XML declaration when saving a document
  • LIBXML_NSCLEAN - Remove redundant namespace declarations
  • LIBXML_PARSEHUGE - Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document and limits of the size of text nodes
  • LIBXML_XINCLUDE - Implement XInclude substitution
  • LIBXML_ERR_ERROR - Get recoverable errors
  • LIBXML_ERR_FATAL - Get fatal errors
  • LIBXML_ERR_NONE - Get no errors
  • LIBXML_ERR_WARNING - Get simple warnings
  • LIBXML_VERSION - Get libxml version (e.g. 20605 or 20617)
  • LIBXML_DOTTED_VERSION - Get dotted libxml version (e.g. 2.6.5 or 2.6.17)
  • nsOptional. Specifies a namespace prefix or URI
    is_prefixOptional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE

    Technical Details

    Return Value: A SimpleXMLElement object on success. FALSE on failure
    PHP Version: 5+

    More Examples

    Assume we have the following XML file, "note.xml": <?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

    Example

    Output the data from each element in the XML file: <?php$xml=simplexml_load_file("note.xml");echo $xml->to . "<br>"; echo $xml->from . "<br>";echo $xml->heading . "<br>";echo $xml->body;?> Run Example »

    Example

    Output the element's name and data for each child node in the XML file: <?php $xml=simplexml_load_file("note.xml"); echo $xml->getName() . "<br>"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br>"; } ?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Convert an XML string into an object, then output keys and elements of the object: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml=simplexml_load_string($note);print_r($xml);?> Run Example »

    Definition and Usage

    The simplexml_load_string() function converts a well-formed XML string into an object.

    Syntax

    simplexml_load_string(data, class, options, ns, is_prefix)

    Parameter Values

    ParameterDescription
    dataRequired. Specifies a well-formed XML string
    classOptional. Specifies the class of the new object
    optionsOptional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
  • LIBXML_COMPACT - Activate nodes allocation optimization (may speed up application)
  • LIBXML_DTDATTR - Set default DTD attributes
  • LIBXML_DTDLOAD - Load external subset
  • LIBXML_DTDVALID - Validate with the DTD
  • LIBXML_NOBLANKS - Remove blank nodes
  • LIBXML_NOCDATA - Merge CDATA as text nodes
  • LIBXML_NOEMPTYTAG - Expand empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
  • LIBXML_NOENT - Substitute entities
  • LIBXML_NOERROR - Do not show error reports
  • LIBXML_NONET - Disable network access while loading documents
  • LIBXML_NOWARNING - Do not show warning reports
  • LIBXML_NOXMLDECL - Drop the XML declaration when saving a document
  • LIBXML_NSCLEAN - Remove redundant namespace declarations
  • LIBXML_PARSEHUGE - Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document and limits of the size of text nodes
  • LIBXML_XINCLUDE - Implement XInclude substitution
  • LIBXML_ERR_ERROR - Get recoverable errors
  • LIBXML_ERR_FATAL - Get fatal errors
  • LIBXML_ERR_NONE - Get no errors
  • LIBXML_ERR_WARNING - Get simple warnings
  • LIBXML_VERSION - Get libxml version (e.g. 20605 or 20617)
  • LIBXML_DOTTED_VERSION - Get dotted libxml version (e.g. 2.6.5 or 2.6.17)
  • nsOptional. Specifies a namespace prefix or URI
    is_prefixOptional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE

    Technical Details

    Return Value: A SimpleXMLElement object on success. FALSE on failure
    PHP Version: 5+

    More Examples

    Example

    Output the data from each element in the XML string: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml=simplexml_load_string($note);echo $xml->to . "<br>";echo $xml->from . "<br>";echo $xml->heading . "<br>";echo $xml->body; ?> Run Example »

    Example

    Output the element's name and data for each child node in the XML string: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml=simplexml_load_string($note);echo $xml->getName() . "<br>"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br>"; }?> Run Example » PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Run an XPath query on the XML document: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLElement($note);$result = $xml->xpath("note/to"); print_r($result);?> Run Example »

    Definition and Usage

    The xpath() function runs an XPath query on the XML document.

    Syntax

    SimpleXMLElement::xpath(path)

    Parameter Values

    ParameterDescription
    pathRequired. Specifies an XPath path to use

    Technical Details

    Return Value: An array of SimpleXMLElements on success. FALSE on failure
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Rewind to the first element and then return it with the current() function: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLIterator($note);// rewind to the first element $xml->rewind();// return current elementvar_dump($xml->current());?> Run Example »

    Definition and Usage

    The current() function returns the current element.

    Syntax

    SimpleXMLIterator::current()

    Technical Details

    Return Value: The current element (as a SimpleXMLIterator object) on success. NULL on failure
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Get the child elements of the current element and output the name and data: <?php$bookxml = <<<XML<bookstore> <book> <title>Everyday Italian</title> <author>Giada De Laurentiis</author> </book> <book> <title>Harry Potter</title> <author>J K. Rowling</author> </book> <book> <title>Learning XML</title> <author>Erik T. Ray</author> </book></bookstore>XML;$xml = new SimpleXMLIterator($bookxml); for( $xml->rewind(); $xml->valid(); $xml->next() ) { foreach($xml->getChildren() as $name => $data) { echo "The $name is '$data'"; echo "<br>"; }}?> Run Example »

    Definition and Usage

    The getChildren() function returns the child elements of the current element.

    Syntax

    SimpleXMLIterator::getChildren()

    Technical Details

    Return Value: A SimpleXMLIterator object containing the children of the current element
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Checks whether the current element has children, if it has; output the current element: <?php$bookxml = <<<XML<bookstore> <book> <title>Everyday Italian</title> <author>Giada De Laurentiis</author> </book> <book> <title>Harry Potter</title> <author>J K. Rowling</author> </book> <book> <title>Learning XML</title> <author>Erik T. Ray</author> </book></bookstore>XML;$xml = new SimpleXMLIterator($bookxml); for( $xml->rewind(); $xml->valid(); $xml->next() ) { if($xml->hasChildren()) { var_dump($xml->current()); echo "<br>"; }}?> Run Example »

    Definition and Usage

    The hasChildren() function checks whether the current element has children.

    Syntax

    SimpleXMLIterator::hasChildren()

    Technical Details

    Return Value: TRUE if the current element has children. FALSE otherwise
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Rewind to the first element and return the current key (which is the XML tag name of the current element): <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLIterator($note);// rewind to the first element $xml->rewind();// return current keyvar_dump($xml->key());?> Run Example »

    Definition and Usage

    The key() function returns the current key (which is the XML tag name of the current element).

    Syntax

    SimpleXMLIterator::key()

    Technical Details

    Return Value: The XML tag name of the current element on success. FALSE otherwise
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Rewind to the first element, move to the next element and then return it with the current() function: <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLIterator($note);// rewind to the first element $xml->rewind();// move to the next element$xml->next();// return current elementvar_dump($xml->current());?> Run Example »

    Definition and Usage

    The next() function moves to the next element.

    Syntax

    SimpleXMLIterator::next()

    Technical Details

    Return Value: Nothing
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Rewind to the first element and then return it (with current()): <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLIterator($note);// rewind to the first element $xml->rewind();// return current elementvar_dump($xml->current());?> Run Example »

    Definition and Usage

    The rewind() function rewinds to the first element.

    Syntax

    SimpleXMLIterator::rewind()

    Technical Details

    Return Value: Nothing
    PHP Version: 5.0+
    PHP SimpleXML Reference PHP SimpleXML Reference

    Example

    Check whether the current element is valid after a call to rewind() and next(): <?php$note=<<<XML<note><to>Tove</to><from>Jani</from><heading>Reminder</heading> <body>Do not forget me this weekend!</body></note>XML; $xml = new SimpleXMLIterator($note);// rewind to the first element $xml->rewind();// check if validvar_dump($xml->valid()); // move to the next element$xml->next();// check if valid var_dump($xml->valid());?> Run Example »

    Definition and Usage

    The valid() function checks whether the current element is valid after a call to rewind() or next().

    Syntax

    SimpleXMLIterator::valid()

    Technical Details

    Return Value: TRUE if element is valid. FALSE otherwise
    PHP Version: 5.0+

    More Examples

    Example

    Check whether the current element is valid after a call to rewind() and next(): <?php$xml = new SimpleXMLIterator('<books><book>Learn PHP</book></books>');// rewind to the first element$xml->rewind(); // check if validvar_dump($xml->valid());// move to the next element$xml->next();// check if valid - will be bool(false) because there is only one elementvar_dump($xml->valid());?> Run Example » PHP SimpleXML Reference

    Stream Introduction

    The Stream functions .... Streams are the way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary location within the stream. A wrapper is additional code which tells the stream how to handle specific protocols/encodings.

    Installation

    The Stream functions are part of the PHP core. There is no installation needed to use these functions.

    Stream Functions

    FunctionDescription
    set_socket_blocking()Deprecated in PHP 5.4, and removed in PHP 7.0. Alias of stream_set_blocking()
    stream_bucket_prepend()
    stream_context_create()
    stream_context_get_default()
    stream_context_get_options()
    stream_context_get_params()
    stream_context_set_default()
    stream_context_set_options()
    stream_context_set_params()
    stream_copy_to_stream()Copies data from one stream to another
    stream_filter_append()Appends a filter to a stream
    stream_filter_prepend()
    stream_filter_register()
    stream_filter_remove()
    stream_get_contents()
    stream_get_filters()
    stream_get_line()
    stream_get_meta_data()
    stream_get_transports()
    stream_get_wrappers()
    stream_is_local()
    stream_isatty()
    stream_notification_callback()
    stream_register_wrapper()Alias of stream_wrapper_register()
    stream_resolve_include_path()
    stream_select()
    stream_set_blocking()
    stream_set_chunk_size()
    stream_set_read_buffer()
    stream_set_timeout()
    stream_set_write_buffer()
    stream_socket_accept()
    stream_socket_client()
    stream_socket_enable_crypto()
    stream_socket_get_name()
    stream_socket_pair()
    stream_socket_recvfrom()
    stream_socket_sendto()
    stream_socket_server()
    stream_socket_shutdown()
    stream_supports_lock()
    stream_wrapper_register()
    stream_wrapper_restore()
    stream_wrapper_unregister()

    String Functions

    The PHP string functions are part of the PHP core. No installation is required to use these functions.
    FunctionDescription
    addcslashes()Returns a string with backslashes in front of the specified characters
    addslashes()Returns a string with backslashes in front of predefined characters
    bin2hex()Converts a string of ASCII characters to hexadecimal values
    chop()Removes whitespace or other characters from the right end of a string
    chr()Returns a character from a specified ASCII value
    chunk_split()Splits a string into a series of smaller parts
    convert_cyr_string()Converts a string from one Cyrillic character-set to another
    convert_uudecode()Decodes a uuencoded string
    convert_uuencode()Encodes a string using the uuencode algorithm
    count_chars()Returns information about characters used in a string
    crc32()Calculates a 32-bit CRC for a string
    crypt()One-way string hashing
    echo()Outputs one or more strings
    explode()Breaks a string into an array
    fprintf()Writes a formatted string to a specified output stream
    get_html_translation_table()Returns the translation table used by htmlspecialchars() and htmlentities()
    hebrev() Converts Hebrew text to visual text
    hebrevc()Converts Hebrew text to visual text and new lines (\n) into <br>
    hex2bin()Converts a string of hexadecimal values to ASCII characters
    html_entity_decode()Converts HTML entities to characters
    htmlentities()Converts characters to HTML entities
    htmlspecialchars_decode()Converts some predefined HTML entities to characters
    htmlspecialchars()Converts some predefined characters to HTML entities
    implode()Returns a string from the elements of an array
    join()Alias of implode()
    lcfirst()Converts the first character of a string to lowercase
    levenshtein()Returns the Levenshtein distance between two strings
    localeconv()Returns locale numeric and monetary formatting information
    ltrim()Removes whitespace or other characters from the left side of a string
    md5()Calculates the MD5 hash of a string
    md5_file()Calculates the MD5 hash of a file
    metaphone()Calculates the metaphone key of a string
    money_format()Returns a string formatted as a currency string
    nl_langinfo()Returns specific local information
    nl2br()Inserts HTML line breaks in front of each newline in a string
    number_format()Formats a number with grouped thousands
    ord()Returns the ASCII value of the first character of a string
    parse_str()Parses a query string into variables
    print()Outputs one or more strings
    printf()Outputs a formatted string
    quoted_printable_decode()Converts a quoted-printable string to an 8-bit string
    quoted_printable_encode()Converts an 8-bit string to a quoted printable string
    quotemeta()Quotes meta characters
    rtrim()Removes whitespace or other characters from the right side of a string
    setlocale()Sets locale information
    sha1()Calculates the SHA-1 hash of a string
    sha1_file()Calculates the SHA-1 hash of a file
    similar_text()Calculates the similarity between two strings
    soundex()Calculates the soundex key of a string
    sprintf()Writes a formatted string to a variable
    sscanf()Parses input from a string according to a format
    str_getcsv()Parses a CSV string into an array
    str_ireplace()Replaces some characters in a string (case-insensitive)
    str_pad()Pads a string to a new length
    str_repeat()Repeats a string a specified number of times
    str_replace()Replaces some characters in a string (case-sensitive)
    str_rot13()Performs the ROT13 encoding on a string
    str_shuffle()Randomly shuffles all characters in a string
    str_split()Splits a string into an array
    str_word_count()Count the number of words in a string
    strcasecmp()Compares two strings (case-insensitive)
    strchr()Finds the first occurrence of a string inside another string (alias of strstr())
    strcmp()Compares two strings (case-sensitive)
    strcoll()Compares two strings (locale based string comparison)
    strcspn()Returns the number of characters found in a string before any part of some specified characters are found
    strip_tags()Strips HTML and PHP tags from a string
    stripcslashes()Unquotes a string quoted with addcslashes()
    stripslashes()Unquotes a string quoted with addslashes()
    stripos()Returns the position of the first occurrence of a string inside another string (case-insensitive)
    stristr()Finds the first occurrence of a string inside another string (case-insensitive)
    strlen()Returns the length of a string
    strnatcasecmp()Compares two strings using a "natural order" algorithm (case-insensitive)
    strnatcmp()Compares two strings using a "natural order" algorithm (case-sensitive)
    strncasecmp()String comparison of the first n characters (case-insensitive)
    strncmp()String comparison of the first n characters (case-sensitive)
    strpbrk()Searches a string for any of a set of characters
    strpos()Returns the position of the first occurrence of a string inside another string (case-sensitive)
    strrchr()Finds the last occurrence of a string inside another string
    strrev()Reverses a string
    strripos()Finds the position of the last occurrence of a string inside another string (case-insensitive)
    strrpos()Finds the position of the last occurrence of a string inside another string (case-sensitive)
    strspn()Returns the number of characters found in a string that contains only characters from a specified charlist
    strstr()Finds the first occurrence of a string inside another string (case-sensitive)
    strtok()Splits a string into smaller strings
    strtolower()Converts a string to lowercase letters
    strtoupper()Converts a string to uppercase letters
    strtr()Translates certain characters in a string
    substr()Returns a part of a string
    substr_compare()Compares two strings from a specified start position (binary safe and optionally case-sensitive)
    substr_count()Counts the number of times a substring occurs in a string
    substr_replace()Replaces a part of a string with another string
    trim()Removes whitespace or other characters from both sides of a string
    ucfirst()Converts the first character of a string to uppercase
    ucwords()Converts the first character of each word in a string to uppercase
    vfprintf()Writes a formatted string to a specified output stream
    vprintf()Outputs a formatted string
    vsprintf()Writes a formatted string to a variable
    wordwrap()Wraps a string to a given number of characters
    PHP String Reference

    Example

    Add a backslash in front of the character "W": <?php $str = addcslashes("Hello World!","W");echo($str); ?> Try it Yourself »

    Definition and Usage

    The addcslashes() function returns a string with backslashes in front of the specified characters. Note: The addcslashes() function is case-sensitive. Note: Be careful using addcslashes() on 0 (NULL), r (carriage return), n (newline), f (form feed), t (tab) and v (vertical tab). In PHP, \0, \r, \n, \t, \f and \v are predefined escape sequences.

    Syntax

    addcslashes(string,characters)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to be escaped
    charactersRequired. Specifies the characters or range of characters to be escaped

    Technical Details

    Return Value: Returns the escaped string
    PHP Version: 4+

    More Examples

    Example

    Add backslashes to certain characters in a string: <?php $str = "Welcome to my humble Homepage!"; echo $str."<br>"; echo addcslashes($str,'m')."<br>"; echo addcslashes($str,'H')."<br>"; ?> Try it Yourself »

    Example

    Add backslashes to a range of characters in a string: <?php $str = "Welcome to my humble Homepage!"; echo $str."<br>"; echo addcslashes($str,'A..Z')."<br>"; echo addcslashes($str,'a..z')."<br>"; echo addcslashes($str,'a..g'); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Add a backslash in front of each double quote ("): <?php $str = addslashes('What does "yolo" mean?');echo($str); ?> Try it Yourself »

    Definition and Usage

    The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are:
  • single quote (')
  • double quote (")
  • backslash (\)
  • NULL
  • Tip: This function can be used to prepare a string for storage in a database and database queries. Note: Prior to PHP 5.4, the PHP dir magic_quotes_gpc was on by default and it ran addslashes() on all GET, POST, and COOKIE data by default. You should not use addslashes() on strings that have already been escaped, as it will cause double escaping. The function get_magic_quotes_gpc() can be used to check this.

    Syntax

    addslashes(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to be escaped

    Technical Details

    Return Value: Returns the escaped string
    PHP Version: 4+
    PHP Changelog: Prior to PHP 5.4, the PHP dir magic_quotes_gpc was on by default and it ran addslashes() on all GET, POST, and COOKIE data by default.

    More Examples

    Example

    Add backslashes to the predefined characters in a string: <?php $str = "Who's Peter Griffin?"; echo $str . " This is not safe in a database query.<br>"; echo addslashes($str) . " This is safe in a database query."; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Convert "Hello World!" to hexadecimal values: <?php $str = bin2hex("Hello World!");echo($str); ?> Try it Yourself »

    Definition and Usage

    The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function.

    Syntax

    bin2hex(string)

    Parameter Values

    ParameterDescription
    stringRequired. The string to be converted

    Technical Details

    Return Value: Returns the hexadecimal value of the converted string
    PHP Version: 4+

    More Examples

    Example

    Convert a string value from binary to hex and back: <?php $str = "Hello world!"; echo bin2hex($str) . "<br>"; echo pack("H*",bin2hex($str)) . "<br>"; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Remove characters from the right end of a string: <?php $str = "Hello World!"; echo $str . "<br>"; echo chop($str,"World!"); ?> Try it Yourself »

    Definition and Usage

    The chop() function removes whitespaces or other predefined characters from the right end of a string.

    Syntax

    chop(string,charlist)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    charlistOptional. Specifies which characters to remove from the string. The following characters are removed if the charlist parameter is empty:
  • "\0" - NULL
  • "\t" - tab
  • "\n" - new line
  • "\x0B" - vertical tab
  • "\r" - carriage return
  • " " - ordinary white space
  • Technical Details

    Return Value: Returns the modified string
    PHP Version: 4+
    Changelog: The charlist parameter was added in PHP 4.1.0

    More Examples

    Example

    Remove newlines (\n) from the right end of a string: <?php$str = "Hello World!\n\n";echo $str;echo chop($str);?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html><body>Hello World!Hello World!</body> </html> The browser output of the code above will be: Hello World! Hello World! Try it Yourself » PHP String Reference PHP String Reference

    Example

    Return characters from different ASCII values: <?php echo chr(52) . "<br>"; // Decimal value echo chr(052) . "<br>"; // Octal value echo chr(0x52) . "<br>"; // Hex value ?> Try it Yourself »

    Definition and Usage

    The chr() function returns a character from the specified ASCII value. The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x.

    Syntax

    chr(ascii)

    Parameter Values

    ParameterDescription
    asciiRequired. An ASCII value

    Technical Details

    Return Value: Returns the specified character
    PHP Version: 4+

    More Examples

    Example

    Using the octal value 046 to add the ASCII Character: &. <?php$str = chr(046); echo("You $str me forever!");?> Try it Yourself »

    Example

    Using the decimal values 43 and 61 to add the ASCII Characters: + and =. <?php $str = chr(43);$str2 = chr(61);echo("2 $str 2 $str2 4"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Split the string after each character and add a "." after each split: <?php $str = "Hello world!"; echo chunk_split($str,1,"."); ?> Try it Yourself »

    Definition and Usage

    The chunk_split() function splits a string into a series of smaller parts. Note: This function does not alter the original string.

    Syntax

    chunk_split(string,length,end)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to split
    lengthOptional. A number that defines the length of the chunks. Default is 76
    endOptional. A string that defines what to place at the end of each chunk. Default is \r\n

    Technical Details

    Return Value: Returns the split string
    PHP Version: 4+

    More Examples

    Example

    Split the string after each sixth character and add a "..." after each split: <?php $str = "Hello world!"; echo chunk_split($str,6,"..."); ?> Try it Yourself » PHP String Reference ❮ PHP String Reference

    Example

    Convert a string from one character-set to another: <?php $str = "Hello world! æøå"; echo $str . "<br>"; echo convert_cyr_string($str,'w','a'); ?> Try it Yourself »

    Definition and Usage

    The convert_cyr_string() function converts a string from one Cyrillic character-set to another. The supported Cyrillic character-sets are:
  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic
  • Note: This function is binary-safe.

    Syntax

    convert_cyr_string(string,from,to)

    Parameter Values

    ParameterDescription
    stringRequired. The string to convert
    fromRequired. A character that specifies what Cyrillic character-set to convert from
    toRequired. A character that specifies what Cyrillic character-set to convert to

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 4+
    ❮ PHP String Reference PHP String Reference

    Example

    Decode a uuencoded string: <?php $str = ",2&5L;&\@=V]R;&0A `"; echo convert_uudecode($str); ?> Try it Yourself »

    Definition and Usage

    The convert_uudecode() function decodes a uuencoded string. This function is often used together with the convert_uuencode() function.

    Syntax

    convert_uudecode(string)

    Parameter Values

    ParameterDescription
    stringRequired. The uuencoded string to decode

    Technical Details

    Return Value: Returns the decoded data as a string
    PHP Version: 5+

    More Examples

    Example

    Encode a string and then decode it: <?php$str = "Hello world!";// Encode the string$encodeString = convert_uuencode($str);echo $encodeString . "<br>";// Decode the string$decodeString = convert_uudecode($encodeString);echo $decodeString; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Encode a string: <?php $str = "Hello world!"; echo convert_uuencode($str); ?> Try it Yourself »

    Definition and Usage

    The convert_uuencode() function encodes a string using the uuencode algorithm. Note: This function encodes all strings (including binary) into printable characters. This will fix any problems with obscure binary data when storing in a database or transmit data over a network. Remember to use the convert_uudecode() function before using the data again. Note: Uuencoded data is about 35% larger than the original.

    Syntax

    convert_uuencode(string)

    Parameter Values

    ParameterDescription
    stringRequired. The string to uuencode

    Technical Details

    Return Value: Returns the uuencoded data
    PHP Version: 5+

    More Examples

    Example

    Encode a string and then decode it: <?php$str = "Hello world!";// Encode the string$encodeString = convert_uuencode($str);echo $encodeString . "<br>";// Decode the string$decodeString = convert_uudecode($encodeString);echo $decodeString; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Return a string with all the different characters used in "Hello World!" (mode 3): <?php $str = "Hello World!"; echo count_chars($str,3); ?> Try it Yourself »

    Definition and Usage

    The count_chars() function returns information about characters used in a string (for example, how many times an ASCII character occurs in a string, or which characters that have been used or not been used in a string).

    Syntax

    count_chars(string,mode)

    Parameter Values

    ParameterDescription
    stringRequired. The string to be checked
    modeOptional. Specifies the return modes. 0 is default. The different return modes are:
  • 0 - an array with the ASCII value as key and number of occurrences as value
  • 1 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences greater than zero
  • 2 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed
  • 3 - a string with all the different characters used
  • 4 - a string with all the unused characters
  • Technical Details

    Return Value: Depending on the specified mode parameter
    PHP Version: 4+

    More Examples

    Example

    Return a string with all the unused characters in "Hello World!" (mode 4): <?php $str = "Hello World!"; echo count_chars($str,4); ?> Try it Yourself »

    Example

    In this example we will use count_chars() with mode 1 to check the string. Mode 1 will return an array with the ASCII value as key and how many times it occurred as value: <?php $str = "Hello World!"; print_r(count_chars($str,1)); ?> Try it Yourself »

    Example

    Another example of counting how many times an ASCII character occurs in a string: <?php$str = "PHP is pretty fun!!";$strArray = count_chars($str,1); foreach ($strArray as $key=>$value) {echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>"; }?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Print the result of crc32(): <?php$str = crc32("Hello World!");printf("%u\n",$str);?> Try it Yourself »

    Definition and Usage

    The crc32() function calculates a 32-bit CRC (cyclic redundancy checksum) for a string. This function can be used to validate data integrity. Tip: To ensure that you get the correct string representation from the crc32() function, you'll need to use the %u formatter of the printf() or sprintf() function. If the %u formatter is not used, the result may display in incorrect and negative numbers.

    Syntax

    crc32(string)

    Parameter Values

    ParameterDescription
    stringRequired. The string to be calculated

    Technical Details

    Return Value: Returns the crc32 checksum of string as an integer
    PHP Version: 4.0.1+

    More Examples

    Example:

    In this example we will print the result of crc32() with and without the "%u" formatter (note that the result is equal): <?php $str = crc32("Hello world!"); echo 'Without %u: '.$str."<br>"; echo 'With %u: '; printf("%u",$str); ?> The output of the code above will be: Without %u: 461707669 With %u: 461707669

    Example:

    In this example we will print the result of crc32() with and without the "%u" formatter (note that the result is not equal): <?php $str = crc32("Hello world."); echo 'Without %u: '.$str."<br>"; echo 'With %u: '; printf("%u",$str); ?> The output of the code above will be: Without %u: -1959132156 With %u: 2335835140 PHP String Reference PHP String Reference

    Definition and Usage

    The crypt() function returns a hashed string using DES, Blowfish, or MD5 algorithms. This function behaves different on different operating systems. PHP checks what algorithms are available and what algorithms to use when it is installed. The salt parameter is optional. However, crypt() creates a weak password without the salt. Make sure to specify a strong enough salt for better security. There are some constants that are used together with the crypt() function. The value of these constants are set by PHP when it is installed. Constants:
  • [CRYPT_STD_DES] - Standard DES-based hash with two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause this function to fail.
  • [CRYPT_EXT_DES] - Extended DES-based hash with a nine character salt consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt. These are encoded as printable characters, 6 bits per character, least significant character first. The values 0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the salt will cause the function to fail.
  • [CRYPT_MD5] - MD5 hashing with a 12 character salt starting with $1$
  • [CRYPT_BLOWFISH] - Blowfish hashing with a salt starting with $2a$, $2x$, or $2y$, a two digit cost parameters "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of the alphabet will cause this function to return a zero-length string. The "$" parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-bashed hashing algorithmeter and must be in range 04-31. Values outside this range will cause the function to fail.
  • [CRYPT_SHA_256] - SHA-256 hash with a 16 character salt starting with $5$. If the salt string starts with "rounds=<N>$", the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  • [CRYPT_SHA_512] - SHA-512 hash with a 16 character salt starting with $6$. If the salt string starts with "rounds=<N>$", the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  • On systems where this function supports multiple algorithms, the constants above are set to "1" if supported and "0" otherwise. Note: There is no decrypt function. The crypt() function uses a one-way algorithm.

    Syntax

    crypt(str,salt)

    Parameter Values

    ParameterDescription
    strRequired. Specifies the string to be hashed
    saltOptional. A salt string to base the hashing on

    Technical Details

    Return Value: Returns the encoded string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure
    PHP Version: 4+
    Changelog: PHP 5.6.0 - Shows a E_NOTICE security warning if salt is omitted. PHP 5.3.7 - Added $2x$ and $2y$ Blowfish modes.PHP 5.3.2 - Added SHA-256 and SHA-512. Fixed Blowfish behavior on invalid rounds returns "failure" string ("*0" or "*1"), instead of falling back to DES.PHP 5.3.0 - PHP now contains its own implementation for MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.

    More Examples

    Example

    In this example we will test the different algorithms: <?php // 2 character salt if (CRYPT_STD_DES == 1){echo "Standard DES: ".crypt('something','st')."\n<br>"; }else{echo "Standard DES not supported.\n<br>";} // 4 character saltif (CRYPT_EXT_DES == 1){echo "Extended DES: ".crypt('something','_S4..some')."\n<br>";}else{echo "Extended DES not supported.\n<br>";}// 12 character salt starting with $1$ if (CRYPT_MD5 == 1){echo "MD5: ".crypt('something','$1$somethin$')."\n<br>"; }else{echo "MD5 not supported.\n<br>";}// Salt starting with $2a$. The two digit cost parameter: 09. 22 characters if (CRYPT_BLOWFISH == 1){ echo "Blowfish: ".crypt('something','$2a$09$anexamplestringforsalt$')."\n<br>"; }else{echo "Blowfish DES not supported.\n<br>";} // 16 character salt starting with $5$. The default number of rounds is 5000.if (CRYPT_SHA256 == 1) {echo "SHA-256: ".crypt('something','$5$rounds=5000$anexamplestringforsalt$')."\n<br>"; } else{echo "SHA-256 not supported.\n<br>";}// 16 character salt starting with $6$. The default number of rounds is 5000. if (CRYPT_SHA512 == 1) {echo "SHA-512: ".crypt('something','$6$rounds=5000$anexamplestringforsalt$'); }else {echo "SHA-512 not supported.";} ?> The output of the code above could be (depending on the operating system): Standard DES: stqAdD7zlbByIExtended DES: _S4..someQXidlBpTUu6MD5: $1$somethin$4NZKrUlY6r7K7.rdEOZ0w.Blowfish: $2a$09$anexamplestringforsaleLouKejcjRlExmf1671qw3Khl49R3dfuSHA-256: $5$rounds=5000$anexamplestringf$KIrctqsxo2wrPg5Ag/hs4jTi4PmoNKQUGWFXlVy9vu9 SHA-512: $6$rounds=5000$anexamplestringf$Oo0skOAdUFXkQxJpwzO05wgRHG0dhuaPBaOU/ oNbGpCEKlf/7oVM5wn6AN0w2vwUgA0O24oLzGQpp1XKI6LLQ0. PHP String Reference PHP String Reference

    Example

    Write some text to the output: <?php echo "Hello world!"; ?> Try it Yourself »

    Definition and Usage

    The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error. Tip: The echo() function is slightly faster than print(). Tip: The echo() function also has a shortcut syntax. Prior to PHP 5.4.0, this syntax only works with the short_open_tag configuration setting enabled.

    Syntax

    echo(strings)

    Parameter Values

    ParameterDescription
    stringsRequired. One or more strings to be sent to the output

    Technical Details

    Return Value: No value is returned
    PHP Version: 4+

    More Examples

    Example

    Write the value of the string variable ($str) to the output: <?php $str = "Hello world!"; echo $str; ?> Try it Yourself »

    Example

    Write the value of the string variable ($str) to the output, including HTML tags: <?php$str = "Hello world!";echo $str;echo "<br>What a nice day!";?> Try it Yourself »

    Example

    Join two string variables together: <?php$str1="Hello world!";$str2="What a nice day!";echo $str1 . " " . $str2;?> Try it Yourself »

    Example

    Write the value of an array to the output: <?php$age=array("Peter"=>"35");echo "Peter is " . $age['Peter'] . " years old.";?> Try it Yourself »

    Example

    Write some text to the output: <?php echo "This text spans multiple lines."; ?> Try it Yourself »

    Example

    How to use multiple parameters: <?php echo 'This ','string ','was ','made ','with multiple parameters.'; ?> Try it Yourself »

    Example

    Difference of single and double quotes. Single quotes will print the variable name, not the value: <?php $color = "red"; echo "Roses are $color"; echo "<br>"; echo 'Roses are $color'; ?> Try it Yourself »

    Example

    Shortcut syntax (will only work with the short_open_tag configuration setting enabled): <?php $color = "red"; ?> <p>Roses are <?=$color?></p> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Break a string into an array: <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> Try it Yourself »

    Definition and Usage

    The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

    Syntax

    explode(separator,string,limit)

    Parameter Values

    ParameterDescription
    separatorRequired. Specifies where to break the string
    stringRequired. The string to split
    limitOptional. Specifies the number of array elements to return. Possible values:
  • Greater than 0 - Returns an array with a maximum of limit element(s)
  • Less than 0 - Returns an array except for the last -limit elements()
  • 0 - Returns an array with one element
  • Technical Details

    Return Value: Returns an array of strings
    PHP Version: 4+
    Changelog: The limit parameter was added in PHP 4.0.1, and support for negative limits were added in PHP 5.1.0

    More Examples

    Example

    Using the limit parameter to return a number of array elements: <?php$str = 'one,two,three,four';// zero limitprint_r(explode(',',$str,0)); // positive limitprint_r(explode(',',$str,2));// negative limit print_r(explode(',',$str,-1));?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Write some text to a text file named "test.txt": <?php$number = 9;$str = "Beijing";$file = fopen("test.txt","w"); echo fprintf($file,"There are %u million bicycles in %s.",$number,$str); ?> The output of the code above will be: 40 The following text will be written to the file "test.txt": There are 9 million bicycles in Beijing.

    Definition and Usage

    The fprintf() function writes a formatted string to a specified output stream (example: file or database). The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: printf(), sprintf(), vprintf(), vsprintf() and vfprintf()

    Syntax

    fprintf(stream,format,arg1,arg2,arg++)

    Parameter Values

    ParameterDescription
    streamRequired. Specifies where to write/output the string
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    arg1Required. The argument to be inserted at the first %-sign in the format string
    arg2Optional. The argument to be inserted at the second %-sign in the format string
    arg++Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

    Technical Details

    Return Value: Returns the length of the written string
    PHP Version: 5+

    More Examples

    Example

    Write some text to a file: <?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"%f",$number); ?> The following text will be written to the file "test.txt": 123.000000

    Example

    Use of placeholders: <?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"With 2 decimals: %1\$.2f \nWith no decimals: %1\$u",$number); ?> The following text will be written to the file "test.txt": With 2 decimals: 123.00 With no decimals: 123

    Example

    Using printf() to demonstrate all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signprintf("%%b = %b <br>",$num1); // Binary numberprintf("%%c = %c <br>",$char); // The ASCII Characterprintf("%%d = %d <br>",$num1); // Signed decimal numberprintf("%%d = %d <br>",$num2); // Signed decimal numberprintf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)printf("%%g = %g <br>",$num1); // Shorter of %e and %fprintf("%%G = %G <br>",$num1); // Shorter of %E and %fprintf("%%o = %o <br>",$num1); // Octal numberprintf("%%s = %s <br>",$num1); // Stringprintf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)printf("%%+d = %+d <br>",$num1); // Sign specifier (positive) printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Print the translation table used by the htmlspecialchars function: <?php print_r (get_html_translation_table()); // HTML_SPECIALCHARS is default. ?> Try it Yourself »

    Definition and Usage

    The get_html_translation_table() function returns the translation table used by the htmlentities() and htmlspecialchars() functions. Tip: Some characters can be encoded several ways. The get_html_translation_table() function returns the most common encoding.

    Syntax

    get_html_translation_table(function,flags,character-set)

    Parameter Values

    ParameterDescription
    functionOptional. Specifies which translation table to return.Possible values:
  • HTML_SPECIALCHARS - Default. Translates some characters that need URL-encoding to be shown properly on a HTML page
  • HTML_ENTITIES - Translates all characters that need URL-encoding to be shown properly on a HTML page
  • flagsOptional. Specifies which quotes the table will contain and which document type the table is for. The available quote styles are:
  • ENT_COMPAT - Default. Table contains entities for double quotes, not single quotes
  • ENT_QUOTES - Table contains entities for double and single quotes
  • ENT_NOQUOTES - Table will not contain entities for double and single quotes
  • Additional flags for specifying which doctype the table is for:
  • ENT_HTML401 - Default. Table for HTML 4.01
  • ENT_HTML5 - Table for HTML 5
  • ENT_XML1 - Table for XML 1
  • ENT_XHTML - Table for XHTML
  • character-setOptional. A string that specifies which character-set to use.Allowed values are:
  • UTF-8 - Default. ASCII compatible multi-byte 8-bit Unicode
  • ISO-8859-1 - Western European
  • ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
  • cp866 - DOS-specific Cyrillic charset
  • cp1251 - Windows-specific Cyrillic charset
  • cp1252 - Windows specific charset for Western European
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, mainly used in Taiwan
  • GB2312 - Simplified Chinese, national standard character set
  • BIG5-HKSCS - Big5 with Hong Kong extensions
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character-set that was used by Mac OS
  • Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.

    Technical Details

    Return Value: Returns the translation table as an array, with the original characters as keys and entities as values
    PHP Version: 4+
    Changelog: The default value for the character-set parameter was changed to UTF-8 in PHP 5The additional flags for specifying which doctype the table is for; ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTML were added in PHP 5.4The character-set parameter was added in PHP 5.3.4

    More Examples

    Example

    Table for HTML_SPECIALCHARS: <?php print_r (get_html_translation_table(HTML_SPECIALCHARS)); ?> Displaying character and entity name: Array ( ["] => &quot; [&] => &amp; [<] => &lt; [>] => &gt; )

    Example

    Table for HTML_ENTITIES: <?php print_r (get_html_translation_table(HTML_ENTITIES)); ?> Displaying character and entity name: Array ( ["] => &quot; [&] => &amp; [<] => &lt; [>] => &gt; [ ] => &nbsp; [¡] => &iexcl; [¢] => &cent; [£] => &pound; [¤] => &curren; [¥] => &yen; [¦] => &brvbar; [§] => &sect; [¨] => &uml; [©] => &copy; [ª] => &ordf; [«] => &laquo; [¬] => &not; [?­] => &shy; [®] => &reg; [¯] => &macr; [°] => &deg; [±] => &plusmn; [²] => &sup2; [³] => &sup3; [´] => &acute; [µ] => &micro; [¶] => &para; [·] => &middot; [¸] => &cedil; [¹] => &sup1; [º] => &ordm; [»] => &raquo; [¼] => &frac14; [½] => &frac12; [¾] => &frac34; [¿] => &iquest; [À] => &Agrave; [Á] => &Aacute; [Â] => &Acirc; [Ã] => &Atilde; [Ä] => &Auml; [Å] => &Aring; [Æ] => &AElig; [Ç] => &Ccedil; [È] => &Egrave; [É] => &Eacute; [Ê] => &Ecirc; [Ë] => &Euml; [Ì] => &Igrave; [Í] => &Iacute; [Î] => &Icirc; [Ï] => &Iuml; [Ð] => &ETH; [Ñ] => &Ntilde; [Ò] => &Ograve; [Ó] => &Oacute; [Ô] => &Ocirc; [Õ] => &Otilde; [Ö] => &Ouml; [×] => &times; [Ø] => &Oslash; [Ù] => &Ugrave; [Ú] => &Uacute; [Û] => &Ucirc; [Ü] => &Uuml; [Ý] => &Yacute; [Þ] => &THORN; [ß] => &szlig; [à] => &agrave; [á] => &aacute; [â] => &acirc; [ã] => &atilde; [ä] => &auml; [å] => &aring; [æ] => &aelig; [ç] => &ccedil; [è] => &egrave; [é] => &eacute; [ê] => &ecirc; [ë] => &euml; [ì] => &igrave; [í] => &iacute; [î] => &icirc; [ï] => &iuml; [ð] => &eth; [ñ] => &ntilde; [ò] => &ograve; [ó] => &oacute; [ô] => &ocirc; [õ] => &otilde; [ö] => &ouml; [÷] => &divide; [ø] => &oslash; [ù] => &ugrave; [ú] => &uacute; [û] => &ucirc; [ü] => &uuml; [ý] => &yacute; [þ] => &thorn; [ÿ] => &yuml; [Œ] => &OElig; [œ] => &oelig; [Š] => &Scaron; [š] => &scaron; [Ÿ] => &Yuml; [ƒ] => &fnof; [ˆ] => &circ; [˜] => &tilde; [Α] => &Alpha; [Β] => &Beta; [Γ] => &Gamma; [Δ] => &Delta; [Ε] => &Epsilon; [Ζ] => &Zeta; [Η] => &Eta; [Θ] => &Theta; [Ι] => &Iota; [Κ] => &Kappa; [Λ] => &Lambda; [Μ] => &Mu; [Ν] => &Nu; [Ξ] => &Xi; [Ο] => &Omicron; [Π] => &Pi; [Ρ] => &Rho; [Σ] => &Sigma; [Τ] => &Tau; [Υ] => &Upsilon; [Φ] => &Phi; [Χ] => &Chi; [Ψ] => &Psi; [Ω] => &Omega; [α] => &alpha; [β] => &beta; [γ] => &gamma; [δ] => &delta; [ε] => &epsilon; [ζ] => &zeta; [η] => &eta; [θ] => &theta; [ι] => &iota; [κ] => &kappa; [λ] => &lambda; [μ] => &mu; [ν] => &nu; [ξ] => &xi; [ο] => &omicron; [π] => &pi; [ρ] => &rho; [ς] => &sigmaf; [σ] => &sigma; [τ] => &tau; [υ] => &upsilon; [φ] => &phi; [χ] => &chi; [ψ] => &psi; [ω] => &omega; [ϑ] => &thetasym; [ϒ] => &upsih; [ϖ] => &piv; [ ] => &ensp; [ ] => &emsp; [ ] => &thinsp; [‌] => &zwnj; [‍] => &zwj; [‎] => &lrm; [‏] => &rlm; [–] => &ndash; [—] => &mdash; [‘] => &lsquo; [’] => &rsquo; [‚] => &sbquo; [“] => &ldquo; [”] => &rdquo; [„] => &bdquo; [†] => &dagger; [‡] => &Dagger; [•] => &bull; […] => &hellip; [‰] => &permil; [′] => &prime; [″] => &Prime; [‹] => &lsaquo; [›] => &rsaquo; [‾] => &oline; [⁄] => &frasl; [€] => &euro; [ℑ] => &image; [℘] => &weierp; [ℜ] => &real; [™] => &trade; [ℵ] => &alefsym; [←] => &larr; [↑] => &uarr; [→] => &rarr; [↓] => &darr; [↔] => &harr; [↵] => &crarr; [⇐] => &lArr; [⇑] => &uArr; [⇒] => &rArr; [⇓] => &dArr; [⇔] => &hArr; [∀] => &forall; [∂] => &part; [∃] => &exist; [∅] => &empty; [∇] => &nabla; [∈] => &isin; [∉] => &notin; [∋] => &ni; [∏] => &prod; [∑] => &sum; [−] => &minus; [∗] => &lowast; [√] => &radic; [∝] => &prop; [∞] => &infin; [∠] => &ang; [∧] => &and; [∨] => &or; [∩] => &cap; [∪] => &cup; [∫] => &int; [∴] => &there4; [∼] => &sim; [≅] => &cong; [≈] => &asymp; [≠] => &ne; [≡] => &equiv; [≤] => &le; [≥] => &ge; [⊂] => &sub; [⊃] => &sup; [⊄] => &nsub; [⊆] => &sube; [⊇] => &supe; [⊕] => &oplus; [⊗] => &otimes; [⊥] => &perp; [⋅] => &sdot; [⌈] => &lceil; [⌉] => &rceil; [⌊] => &lfloor; [⌋] => &rfloor; [〈] => &lang; [〉] => &rang; [◊] => &loz; [♠] => &spades; [♣] => &clubs; [♥] => &hearts; [♦] => &diams; ) PHP String Reference ❮ PHP String Reference

    Example

    Reverse the display of Hebrew characters: <?php echo hebrev("á çùåï äúùñâ"); ?> Try it Yourself »

    Definition and Usage

    The hebrev() function converts Hebrew text from a right-to-left flow to a left-to-right flow. Tip: hebrev() and hebrevc() can convert Hebrew logical text (the Windows encoding) to Hebrew visual text. Hebrew visual requires no special right-to-left character support to be displayed properly, making it very useful for displaying Hebrew text on the web.

    Syntax

    hebrev(string,maxcharline)

    Parameter Values

    ParameterDescription
    stringRequired. A Hebrew text
    maxcharlineOptional. Specifies maximum characters for each line. hebrev() will avoid breaking words if possible

    Technical Details

    Return Value: Returns the visual string
    PHP Version: 4+
    ❮ PHP String Reference PHP String Reference

    Example

    Reverse the display of Hebrew characters, and convert new lines(\n) into <br>: <?php echo hebrevc("??? ???\n??? ???"); ?> Try it Yourself »

    Definition and Usage

    The hebrevc() function converts Hebrew text from a right-to-left flow to a left-to-right flow. It also converts new lines (\n) into <br>. Tip: hebrevc() and hebrev() can convert Hebrew logical text (the Windows encoding) to Hebrew visual text. Hebrew visual requires no special right-to-left character support to be displayed properly, making it very useful for displaying Hebrew text on the web.

    Syntax

    hebrevc(string,maxcharline)

    Parameter Values

    ParameterDescription
    stringRequired. A Hebrew text
    maxcharlineOptional. Specifies maximum characters for each line. hebrev() will avoid breaking words if possible

    Technical Details

    Return Value: Returns the visual string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Convert hexadecimal values to ASCII characters: <?phpecho hex2bin("48656c6c6f20576f726c6421"); ?> Try it Yourself »

    Definition and Usage

    The hex2bin() function converts a string of hexadecimal values to ASCII characters.

    Syntax

    hex2bin(string)

    Parameter Values

    ParameterDescription
    stringRequired. The hexadecimal value to be converted

    Technical Details

    Return Value: Returns the ASCII character of the converted string, or FALSE on failure
    PHP Version: 5.4.0+
    Changelog: PHP 5.5.1 - Throws a warning if the string is invalid hexadecimal string.PHP 5.4.1 - Throws a warning if the string is of odd length. In 5.4.0, the string was silently accepted, but the last byte was removed.
    PHP String Reference ❮ PHP String Reference

    Example

    Convert HTML entities to characters: <?php$str = '&lt;a href=&quot;https://www.w3schools.com&quot;&gt;w3schools.com&lt;/a&gt;'; echo html_entity_decode($str); ?> The HTML output of the code above will be (View Source): <a href="https://www.w3schools.com">w3schools.com</a> The browser output of the code above will be: w3schools.com

    Definition and Usage

    The html_entity_decode() function converts HTML entities to characters. The html_entity_decode() function is the opposite of htmlentities().

    Syntax

    html_entity_decode(string,flags,character-set)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to decode
    flagsOptional. Specifies how to handle quotes and which document type to use. The available quote styles are:
  • ENT_COMPAT - Default. Decodes only double quotes
  • ENT_QUOTES - Decodes double and single quotes
  • ENT_NOQUOTES - Does not decode any quotes
  • Additional flags for specifying the used doctype:
  • ENT_HTML401 - Default. Handle code as HTML 4.01
  • ENT_HTML5 - Handle code as HTML 5
  • ENT_XML1 - Handle code as XML 1
  • ENT_XHTML - Handle code as XHTML
  • character-setOptional. A string that specifies which character-set to use.Allowed values are:
  • UTF-8 - Default. ASCII compatible multi-byte 8-bit Unicode
  • ISO-8859-1 - Western European
  • ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
  • cp866 - DOS-specific Cyrillic charset
  • cp1251 - Windows-specific Cyrillic charset
  • cp1252 - Windows specific charset for Western European
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, mainly used in Taiwan
  • GB2312 - Simplified Chinese, national standard character set
  • BIG5-HKSCS - Big5 with Hong Kong extensions
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character-set that was used by Mac OS
  • Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 4.3.0+
    Changelog: PHP 5.6 - Changed the default value for the character-set parameter to the value of the default charset (in configuration).PHP 5.4 - Changed the default value for the character-set parameter to UTF-8. PHP 5.4 - Added ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTML.PHP 5.0 - Added support for multi-byte encodings

    More Examples

    Example

    Convert some HTML entities to characters: <?php $str = "Albert Einstein said: &#039;E=MC&sup2;&#039;";echo html_entity_decode($str, ENT_COMPAT); // Will only convert double quotes echo "<br>";echo html_entity_decode($str, ENT_QUOTES); // Converts double and single quotes echo "<br>";echo html_entity_decode($str, ENT_NOQUOTES); // Does not convert any quotes ?> The HTML output of the code above will be (View Source): Albert Einstein said: &#039;E=MC²&#039;<br>Albert Einstein said: 'E=MC²'<br> Albert Einstein said: &#039;E=MC²&#039; The browser output of the code above will be: Albert Einstein said: 'E=MC²'Albert Einstein said: 'E=MC²'Albert Einstein said: 'E=MC²'

    Example

    Convert some HTML entities to characters, using the Western European character-set: <?php $str = "My name is &Oslash;yvind &Aring;sane. I&#039;m Norwegian."; echo html_entity_decode($str, ENT_QUOTES, "UTF-8"); ?> The HTML output of the code above will be (View Source): My name is Øyvind Åsane. I'm Norwegian. The browser output of the code above will be: My name is Øyvind Åsane. I'm Norwegian. ❮ PHP String Reference PHP String Reference

    Example

    Convert some characters to HTML entities: <?php$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';echo htmlentities($str); ?> The HTML output of the code above will be (View Source): &lt;a href=&quot;https://www.w3schools.com&quot;&gt;Go to w3schools.com&lt;/a&gt; The browser output of the code above will be: <a href="https://www.w3schools.com">Go to w3schools.com</a> Try it Yourself »

    Definition and Usage

    The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().

    Syntax

    htmlentities(string,flags,character-set,double_encode)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert
    flagsOptional. Specifies how to handle quotes, invalid encoding and the used document type.The available quote styles are:
  • ENT_COMPAT - Default. Encodes only double quotes
  • ENT_QUOTES - Encodes double and single quotes
  • ENT_NOQUOTES - Does not encode any quotes
  • Invalid encoding:
  • ENT_IGNORE - Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.
  • ENT_SUBSTITUTE - Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
  • ENT_DISALLOWED - Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
  • Additional flags for specifying the used doctype:
  • ENT_HTML401 - Default. Handle code as HTML 4.01
  • ENT_HTML5 - Handle code as HTML 5
  • ENT_XML1 - Handle code as XML 1
  • ENT_XHTML - Handle code as XHTML
  • character-setOptional. A string that specifies which character-set to use.Allowed values are:
  • UTF-8 - Default. ASCII compatible multi-byte 8-bit Unicode
  • ISO-8859-1 - Western European
  • ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
  • cp866 - DOS-specific Cyrillic charset
  • cp1251 - Windows-specific Cyrillic charset
  • cp1252 - Windows specific charset for Western European
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, mainly used in Taiwan
  • GB2312 - Simplified Chinese, national standard character set
  • BIG5-HKSCS - Big5 with Hong Kong extensions
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character-set that was used by Mac OS
  • Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.
    double_encodeOptional. A boolean value that specifies whether to encode existing html entities or not.
  • TRUE - Default. Will convert everything
  • FALSE - Will not encode existing html entities
  • Technical Details

    Return Value: Returns the converted string. However, if the string parameter contains invalid encoding, it will return an empty string, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set
    PHP Version: 4+
    Changelog: PHP 5.6 - Changed the default value for the character-set parameter to the value of the default charset (in configuration).PHP 5.4 - Changed the default value for the character-set parameter to UTF-8. PHP 5.4 - Added ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTMLPHP 5.3 - Added ENT_IGNORE constant.PHP 5.2.3 - Added the double_encode parameter.PHP 4.1 - Added the character-set parameter.

    More Examples

    Example

    Convert some characters to HTML entities: <?php $str = "Albert Einstein said: 'E=MC²'"; echo htmlentities($str, ENT_COMPAT); // Will only convert double quotes echo "<br>"; echo htmlentities($str, ENT_QUOTES); // Converts double and single quotes echo "<br>"; echo htmlentities($str, ENT_NOQUOTES); // Does not convert any quotes ?> The HTML output of the code above will be (View Source): Albert Einstein said: 'E=MC&sup2;'<br>Albert Einstein said: &#039;E=MC&sup2;&#039;<br>Albert Einstein said: 'E=MC&sup2;' The browser output of the code above will be: Albert Einstein said: 'E=MC²'Albert Einstein said: 'E=MC²'Albert Einstein said: 'E=MC²' Try it Yourself »

    Example

    Convert some characters to HTML entities using the Western European character-set: <?php$str = "My name is Øyvind Åsane. I'm Norwegian.";echo htmlentities($str, ENT_QUOTES, "UTF-8"); // Will only convert double quotes (not single quotes), and uses the character-set Western European?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html><body>My name is &Oslash;yvind &Aring;sane. I&#039;m Norwegian.</body></html> The browser output of the code above will be: My name is Øyvind Åsane. I'm Norwegian. Try it Yourself » PHP String Reference PHP String Reference

    Example

    Convert the predefined HTML entities "&lt;" (less than) and "&gt;" (greater than) to characters: <?php$str = "This is some &lt;b&gt;bold&lt;/b&gt; text.";echo htmlspecialchars_decode($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> This is some <b>bold</b> text. </body> </html> The browser output of the code above will be: This is some bold text.

    Definition and Usage

    The htmlspecialchars_decode() function converts some predefined HTML entities to characters. HTML entities that will be decoded are:
  • &amp; becomes & (ampersand)
  • &quot; becomes " (double quote)
  • &#039; becomes ' (single quote)
  • &lt; becomes < (less than)
  • &gt; becomes > (greater than)
  • The htmlspecialchars_decode() function is the opposite of htmlspecialchars().

    Syntax

    htmlspecialchars_decode(string,flags)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to decode
    flagsOptional. Specifies how to handle quotes and which document type to use.The available quote styles are:
  • ENT_COMPAT - Default. Decodes only double quotes
  • ENT_QUOTES - Decodes double and single quotes
  • ENT_NOQUOTES - Does not decode any quotes
  • Additional flags for specifying the used doctype:
  • ENT_HTML401 - Default. Handle code as HTML 4.01
  • ENT_HTML5 - Handle code as HTML 5
  • ENT_XML1 - Handle code as XML 1
  • ENT_XHTML - Handle code as XHTML
  • Technical Details

    Return Value: Returns the converted string
    PHP Version: 5.1.0+
    Changelog: PHP 5.4 - Added ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTML.

    More Examples

    Example

    Convert some predefined HTML entities to characters: <?php $str = "Jane &amp; &#039;Tarzan&#039;"; echo htmlspecialchars_decode($str, ENT_COMPAT); // Will only convert double quotes echo "<br>"; echo htmlspecialchars_decode($str, ENT_QUOTES); // Converts double and single quotes echo "<br>"; echo htmlspecialchars_decode($str, ENT_NOQUOTES); // Does not convert any quotes ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Jane & &#039;Tarzan&#039;<br> Jane & 'Tarzan'<br> Jane & &#039;Tarzan&#039; </body> </html> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan'

    Example

    Convert the predefined HTML entities to double quotes: <?php $str = 'I love &quot;PHP&quot;.';echo htmlspecialchars_decode($str, ENT_QUOTES); // Converts double and single quotes ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> I love "PHP". </body> </html> The browser output of the code above will be: I love "PHP". PHP String Reference PHP String Reference

    Example

    Convert the predefined characters "<" (less than) and ">" (greater than) to HTML entities: <?php$str = "This is some <b>bold</b> text.";echo htmlspecialchars($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> This is some &lt;b&gt;bold&lt;/b&gt; text. </body> </html> The browser output of the code above will be: This is some <b>bold</b> text. Try it Yourself »

    Definition and Usage

    The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are:
  • & (ampersand) becomes &amp;
  • " (double quote) becomes &quot;
  • ' (single quote) becomes &#039;
  • < (less than) becomes &lt;
  • > (greater than) becomes &gt;
  • Tip: To convert special HTML entities back to characters, use the htmlspecialchars_decode() function.

    Syntax

    htmlspecialchars(string,flags,character-set,double_encode)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert
    flagsOptional. Specifies how to handle quotes, invalid encoding and the used document type.The available quote styles are:
  • ENT_COMPAT - Default. Encodes only double quotes
  • ENT_QUOTES - Encodes double and single quotes
  • ENT_NOQUOTES - Does not encode any quotes
  • Invalid encoding:
  • ENT_IGNORE - Ignores invalid encoding instead of having the function return an empty string. Should be avoided, as it may have security implications.
  • ENT_SUBSTITUTE - Replaces invalid encoding for a specified character set with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
  • ENT_DISALLOWED - Replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
  • Additional flags for specifying the used doctype:
  • ENT_HTML401 - Default. Handle code as HTML 4.01
  • ENT_HTML5 - Handle code as HTML 5
  • ENT_XML1 - Handle code as XML 1
  • ENT_XHTML - Handle code as XHTML
  • character-setOptional. A string that specifies which character-set to use.Allowed values are:
  • UTF-8 - Default. ASCII compatible multi-byte 8-bit Unicode
  • ISO-8859-1 - Western European
  • ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)
  • cp866 - DOS-specific Cyrillic charset
  • cp1251 - Windows-specific Cyrillic charset
  • cp1252 - Windows specific charset for Western European
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, mainly used in Taiwan
  • GB2312 - Simplified Chinese, national standard character set
  • BIG5-HKSCS - Big5 with Hong Kong extensions
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character-set that was used by Mac OS
  • Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.
    double_encodeOptional. A boolean value that specifies whether to encode existing html entities or not.
  • TRUE - Default. Will convert everything
  • FALSE - Will not encode existing html entities
  • Technical Details

    Return Value: Returns the converted stringIf the string contains invalid encoding, it will return an empty string, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set
    PHP Version: 4+
    Changelog: PHP 5.6 - Changed the default value for the character-set parameter to the value of the default charset (in configuration).PHP 5.4 - Changed the default value for the character-set parameter to UTF-8. PHP 5.4 - Added ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTMLPHP 5.3 - Added ENT_IGNORE constant.PHP 5.2.3 - Added the double_encode parameter.PHP 4.1 - Added the character-set parameter.

    More Examples

    Example

    Convert some predefined characters to HTML entities: <?php $str = "Jane & 'Tarzan'"; echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes echo "<br>"; echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes echo "<br>"; echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Jane &amp; 'Tarzan'<br> Jane &amp; &#039;Tarzan&#039;<br> Jane &amp; 'Tarzan' </body> </html> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan' Try it Yourself »

    Example

    Convert double quotes to HTML entities: <?php $str = 'I love "PHP".';echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> I love &quot;PHP&quot;. </body> </html> The browser output of the code above will be: I love "PHP". Try it Yourself » PHP String Reference PHP String Reference

    Example

    Join array elements with a string: <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> Try it Yourself »

    Definition and Usage

    The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility. Note: This function is binary-safe.

    Syntax

    implode(separator,array)

    Parameter Values

    ParameterDescription
    separatorOptional. Specifies what to put between the array elements. Default is " (an empty string)
    arrayRequired. The array to join to a string

    Technical Details

    Return Value: Returns a string from elements of an array
    PHP Version: 4+
    Changelog: The separator parameter became optional in PHP 4.3.0

    More Examples

    Example

    Separate the array elements with different characters: <?php$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr)."<br>";echo implode("+",$arr)."<br>";echo implode("-",$arr)."<br>"; echo implode("X",$arr);?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Join array elements with a string: <?php $arr = array('Hello','World!','Beautiful','Day!'); echo join(" ",$arr); ?> Try it Yourself »

    Definition and Usage

    The join() function returns a string from the elements of an array. The join() function is an alias of the implode() function. Note: The join() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of join() is optional. However, it is recommended to always use two parameters for backwards compatibility.

    Syntax

    join(separator,array)

    Parameter Values

    ParameterDescription
    separatorOptional. Specifies what to put between the array elements. Default is " (an empty string)
    arrayRequired. The array to join to a string

    Technical Details

    Return Value: Returns a string from elements of an array
    PHP Version: 4+
    Changelog: The separator parameter became optional in PHP 4.3.0.

    More Examples

    Example

    Separate the array elements with different characters: <?php$arr = array('Hello','World!','Beautiful','Day!');echo join(" ",$arr)."<br>";echo join("+",$arr)."<br>";echo join("-",$arr)."<br>"; echo join("X",$arr);?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Convert the first character of "Hello" to lowercase: <?phpecho lcfirst("Hello world!");?> Try it Yourself »

    Definition and Usage

    The lcfirst() function converts the first character of a string to lowercase. Related functions:
  • ucfirst() - converts the first character of a string to uppercase
  • ucwords() - converts the first character of each word in a string to uppercase
  • strtoupper() - converts a string to uppercase
  • strtolower() - converts a string to lowercase
  • Syntax

    lcfirst(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 5.3.0+
    PHP String Reference PHP String Reference

    Example

    Calculate the Levenshtein distance between two strings: <?php echo levenshtein("Hello World","ello World"); echo "<br>"; echo levenshtein("Hello World","ello World",10,20,30); ?> Try it Yourself »

    Definition and Usage

    The levenshtein() function returns the Levenshtein distance between two strings. The Levenshtein distance is the number of characters you have to replace, insert or delete to transform string1 into string2. By default, PHP gives each operation (replace, insert, and delete) equal weight. However, you can define the cost of each operation by setting the optional insert, replace, and delete parameters. Note: The levenshtein() function is not case-sensitive. Note: The levenshtein() function is faster than the similar_text() function. However, similar_text() will give you a more accurate result with less modifications needed.

    Syntax

    levenshtein(string1,string2,insert,replace,delete)

    Parameter Values

    ParameterDescription
    string1Required. First string to compare
    string2Required. Second string to compare
    insertOptional. The cost of inserting a character. Default is 1
    replaceOptional. The cost of replacing a character. Default is 1
    deleteOptional. The cost of deleting a character. Default is 1

    Technical Details

    Return Value: Returns the Levenshtein distance between the two argument strings or -1, if one of the strings exceeds 255 characters
    PHP Version: 4.0.1+
    PHP String Reference PHP String Reference

    Example

    Find the United States locale numeric formatting information: <?php setlocale(LC_ALL,"US"); $locale_info = localeconv(); print_r($locale_info); ?> Try it Yourself »

    Definition and Usage

    The localeconv() function returns an array containing local numeric and monetary formatting information. The localeconv() function will return the following array elements:
  • [decimal_point] - Decimal point character
  • [thousands_sep] - Thousands separator
  • [int_curr_symbol] - Currency symbol (example: USD)
  • [currency_symbol] - Currency symbol (example: $)
  • [mon_decimal_point] - Monetary decimal point character
  • [mon_thousands_sep] - Monetary thousands separator
  • [positive_sign] - Positive value character
  • [negative_sign] - Negative value character
  • [int_frac_digits] - International fractional digits
  • [frac_digits] - Local fractional digits
  • [p_cs_precedes] - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind
  • [p_sep_by_space] - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise
  • [n_cs_precedes] - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind
  • [n_sep_by_space] - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise
  • [p_sign_posn] - Formatting options:
  • 0 - Parentheses surround the quantity and currency symbol
  • 1 - The + sign is placed in front of the quantity and currency symbol
  • 2 - The + sign is placed after the quantity and currency symbol
  • 3 - The + sign is placed immediately in front of the currency symbol
  • 4 - The + sign is placed immediately after the currency symbol
  • [n_sign_posn] - Formatting options:
  • 0 - Parentheses surround the quantity and currency symbol
  • 1 - The - sign is placed in front of the quantity and currency symbol
  • 2 - The - sign is placed after the quantity and currency symbol
  • 3 - The - sign is placed immediately in front of the currency symbol
  • 4 - The - sign is placed immediately after the currency symbol
  • [grouping] - Array displaying how numbers are grouped (example: 3 indicates 1 000 000)
  • [mon_grouping] - Array displaying how monetary numbers are grouped (example: 2 indicates 1 00 00 00)
  • Tip: To define locale settings, see the setlocale() function. Tip: To view all available language codes, go to our Language code reference.

    Syntax

    localeconv()

    Technical Details

    Return Value: Returns data based upon the current locale as set by setlocale()
    PHP Version: 4.0.5+
    PHP String Reference PHP String Reference

    Example

    Remove characters from the left side of a string: <?php $str = "Hello World!"; echo $str . "<br>"; echo ltrim($str,"Hello"); ?> Try it Yourself »

    Definition and Usage

    The ltrim() function removes whitespace or other predefined characters from the left side of a string. Related functions:
  • rtrim() - Removes whitespace or other predefined characters from the right side of a string
  • trim() - Removes whitespace or other predefined characters from both sides of a string
  • Syntax

    ltrim(string,charlist)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    charlistOptional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
  • "\0" - NULL
  • "\t" - tab
  • "\n" - new line
  • "\x0B" - vertical tab
  • "\r" - carriage return
  • " " - ordinary white space
  • Technical Details

    Return Value: Returns the modified string
    PHP Version: 4+
    Changelog: The charlist parameter was added in PHP 4.1

    More Examples

    Example

    Remove whitespaces from the left side of a string: <?php $str = " Hello World!"; echo "Without ltrim: " . $str; echo "<br>"; echo "With ltrim: " . ltrim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without ltrim: Hello World!<br>With ltrim: Hello World! </body> </html> The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World! Try it Yourself »

    Example

    Remove newlines (\n) from the left side of a string: <?php $str = "\n\n\nHello World!"; echo "Without ltrim: " . $str; echo "<br>"; echo "With ltrim: " . ltrim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without ltrim: Hello World!<br>With ltrim: Hello World! </body> </html> The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World! Try it Yourself » PHP String Reference PHP String Reference

    Example

    Calculate the MD5 hash of the string "Hello": <?php $str = "Hello"; echo md5($str); ?> Try it Yourself »

    Definition and Usage

    The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." To calculate the MD5 hash of a file, use the md5_file() function.

    Syntax

    md5(string,raw)

    Parameter Values

    ParameterDescription
    stringRequired. The string to be calculated
    rawOptional. Specifies hex or binary output format:
  • TRUE - Raw 16 character binary format
  • FALSE - Default. 32 character hex number
  • Technical Details

    Return Value: Returns the calculated MD5 hash on success, or FALSE on failure
    PHP Version: 4+
    Changelog: The raw parameter became optional in PHP 5.0

    More Examples

    Example

    Print the result of md5(): <?php $str = "Hello"; echo "The string: ".$str."<br>"; echo "TRUE - Raw 16 character binary format: ".md5($str, TRUE)."<br>"; echo "FALSE - 32 character hex number: ".md5($str)."<br>"; ?> Try it Yourself »

    Example

    Print the result of md5() and then test it: <?php$str = "Hello";echo md5($str);if (md5($str) == "8b1a9953c4611296a827abf8c47804d7") { echo "<br>Hello world!"; exit; }?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Calculate the MD5 hash of the text file "test.txt": <?php $filename = "test.txt"; $md5file = md5_file($filename); echo $md5file; ?> The output of the code above will be: d41d8cd98f00b204e9800998ecf8427e

    Definition and Usage

    The md5_file() function calculates the MD5 hash of a file. The md5_file() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." To calculate the MD5 hash of a string, use the md5() function.

    Syntax

    md5_file(file,raw)

    Parameter Values

    ParameterDescription
    fileRequired. The file to be calculated
    rawOptional. A boolean value that specifies hex or binary output format:
  • TRUE - Raw 16 character binary format
  • FALSE - Default. 32 character hex number
  • Technical Details

    Return Value: Returns the calculated MD5 hash on success, or FALSE on failure
    PHP Version: 4.2.0+
    Changelog: The raw parameter was added in PHP 5.0As of PHP 5.1, it is possible to use md5_file() with wrappers, e.g. md5_file("https://w3schools.com/..")

    More Examples

    Example

    Store the MD5 hash of "test.txt" in a file: <?php $md5file = md5_file("test.txt"); file_put_contents("md5file.txt",$md5file); ?> Test if "test.txt" has been changed (that is if the MD5 hash has been changed): <?php $md5file = file_get_contents("md5file.txt"); if (md5_file("test.txt") == $md5file) { echo "The file is ok."; } else { echo "The file has been changed."; } ?> The output of the code above could be: The file is ok. PHP String Reference PHP String Reference

    Example

    Calculate the metaphone key of "World": <?php echo metaphone("World"); ?> Try it Yourself »

    Definition and Usage

    The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications. Note: The metaphone() function creates the same key for similar sounding words. Note: The generated metaphone keys vary in length. Tip: metaphone() is more accurate than the soundex() function, because metaphone() knows the basic rules of English pronunciation.

    Syntax

    metaphone(string,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    lengthOptional. Specifies the maximum length of the metaphone key

    Technical Details

    Return Value: Returns the metaphone key of the string on success, or FALSE on failure.
    PHP Version: 4+

    More Examples

    Example

    Using the metaphone() function on two similar sounding words: <?php $str = "Assistance"; $str2 = "Assistants"; echo metaphone($str); echo "<br>"; echo metaphone($str2); ?> Try it Yourself »

    Example

    Using the length parameter: <?php $str = "Assistance"; $str2 = "Assistants"; echo metaphone($str,5); echo "<br>"; echo metaphone($str2,5); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    International en_US format: <?php $number = 1234.56; setlocale(LC_MONETARY,"en_US"); echo money_format("The price is %i", $number); ?> The output of the code above will be: The price is USD 1,234.56

    Definition and Usage

    The money_format() function returns a string formatted as a currency string. This function inserts a formatted number where there is a percent (%) sign in the main string. Note: The money_format() function does not work on Windows platforms. Tip: This function is often used together with the setlocale() function. Tip: To view all available language codes, go to our Language code reference.

    Syntax

    money_format(string,number)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to be formatted and how to format the variables in it.Possible format values: Padding and Flags:
  • =f - Specifies the character (f) to be used as padding (Example: %=t this uses "t" as padding). Default is space
  • ^ - Removes the use of grouping characters
  • + or ( - Specifies how to show positive and negative numbers. If "+" is used, the local setting for + and - will be used (usually a sign in front of negative numbers, and nothing in front of positive numbers). If "(" is used, negative numbers are enclosed in parenthesis. Default is "+"
  • ! - Stops the use of currency symbols in the output string
  • - If "-" is used, all fields are left-justified. Default is right-justified
  • Field width:
  • x - Specifies the minimum field width (x). Default is 0
  • #x - Specifies the maximum number (x) of digits expected to the left of the decimal point. This is used to keep formatted output aligned in the same columns. If the number of digits are bigger than x, this specification is ignored
  • .x - Specifies the maximum number (x) of digits expected to the right of the decimal point. If x is 0, the decimal point and the digits to its right will not be shown. Default is local settings
  • Conversion characters:
  • i - The number is formatted to international currency format
  • n - The number is formatted to national currency format
  • % - Returns the % character
  • Note: If multiple format values are used, they must be in the same order as shown above. Note: This function is affected by local settings.
    numberRequired. The number to be inserted at the %-sign in the format string

    Technical Details

    Return Value: Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING
    PHP Version: 4.3.0+

    More Examples

    Example

    International format (Germany) with 2 decimals: <?php $number = 1234.56; setlocale(LC_MONETARY,"de_DE"); echo money_format("%.2n", $number); ?> The output of the code above will be: 1 234,56 EUR

    Example

    Negative number, US national format with () to indicate negative numbers and 2 digits of right precision and "*" as a fill character: <?php $number = -1234.5672; echo money_format("%=*(#10.2n",$number); ?> The output of the code above will be: (******1234.57) PHP String Reference PHP String Reference

    Definition and Usage

    The nl_langinfo() function returns specific local information. Note: This function does not work on Windows platforms. Tip: Unlike the localeconv() function, which returns all local formatting information, the nl_langinfo() function returns specific information.

    Syntax

    nl_langinfo(element)

    Parameter Values

    ParameterDescription
    elementRequired. Specifies which element to return. Must be one of the following elements:Time and Calendar:
  • ABDAY_(1-7) - Abbreviated name of the numbered day of the week
  • DAY_(1-7) - Name of the numbered day of the week (DAY_1 = Sunday)
  • ABMON_(1-12) - Abbreviated name of the numbered month of the year
  • MON_(1-12) - Name of the numbered month of the year
  • AM_STR - String for Ante meridian
  • PM_STR - String for Post meridian
  • D_T_FMT - String that can be used as the format string for strftime() to represent time and date
  • D_FMT - String that can be used as the format string for strftime() to represent date
  • T_FMT - String that can be used as the format string for strftime() to represent time
  • T_FMT_AMPM - String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian
  • ERA - Alternate era
  • ERA_YEAR - Year in alternate era format
  • ERA_D_T_FMT - Date and time in alternate era format (string can be used in strftime())
  • ERA_D_FMT - Date in alternate era format (string can be used in strftime())
  • ERA_T_FMT - Time in alternate era format (string can be used in strftime())
  • Monetary Category:
  • INT_CURR_SYMBOL - Currency symbol (example: USD)
  • CURRENCY_SYMBOL - Currency symbol (example: $)
  • CRNCYSTR - Same as CURRENCY_SYMBOL
  • MON_DECIMAL_POINT - Monetary decimal point character
  • MON_THOUSANDS_SEP - Monetary thousands separator
  • POSITIVE_SIGN - Positive value character
  • NEGATIVE_SIGN -Negative value character
  • MON_GROUPING - Array displaying how monetary numbers are grouped (example: 1 000 000)
  • INT_FRAC_DIGITS - International fractional digits
  • FRAC_DIGITS - Local fractional digits
  • P_CS_PRECEDES - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind
  • P_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise
  • N_CS_PRECEDES - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind
  • N_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise
  • P_SIGN_POSN - Formatting setting. Possible return values:
  • 0 - Parentheses surround the quantity and currency symbol
  • 1 - The sign string is placed in front of the quantity and currency symbol
  • 2 - The sign string is placed after the quantity and currency symbol
  • 3 - The sign string is placed immediately in front of the currency symbol
  • 4 - The sign string is placed immediately after the currency symbol
  • N_SIGN_POSN - Formatting setting. Possible return values:
  • 0 - Parentheses surround the quantity and currency symbol
  • 1 - The sign string is placed in front of the quantity and currency symbol
  • 2 - The sign string is placed after the quantity and currency symbol
  • 3 - The sign string is placed immediately in front of the currency symbol
  • 4 - The sign string is placed immediately after the currency symbol
  • Numeric Category:
  • DECIMAL_POINT - Decimal point character
  • RADIXCHAR - Same as DECIMAL_POINT
  • THOUSANDS_SEP - Separator character for thousands
  • THOUSEP - Same as THOUSANDS_SEP
  • GROUPING - Array displaying how numbers are grouped (example: 1 000 000)
  • Messaging Category:
  • YESEXPR - Regex string for matching 'yes' input
  • NOEXPR - Regex string for matching 'no' input
  • YESSTR - Output string for 'yes'
  • NOSTR - Output string for 'no'
  • Code set Category:
  • CODESET Return a string with the name of the character encoding.
  • Technical Details

    Return Value: Returns the specific information on success, or FALSE on failure.
    PHP Version: 4.1.0+
    PHP String Reference PHP String Reference

    Example

    Insert line breaks where newlines (\n) occur in the string: <?php echo nl2br("One line.\nAnother line."); ?> The browser output of the code above will be: One line. Another line. The HTML output of the code above will be (View Source): One line.<br /> Another line. Try it Yourself »

    Definition and Usage

    The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.

    Syntax

    nl2br(string,xhtml)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    xhtml Optional. A boolean value that indicates whether or not to use XHTML compatible line breaks:
  • TRUE- Default. Inserts <br />
  • FALSE - Inserts <br>
  • Technical Details

    Return Value: Returns the converted string
    PHP Version: 4+
    Changelog: The xhtml parameter was added in PHP 5.3.Before PHP 4.0.5, it inserted <br>. After PHP 4.0.5 it inserts <br />.

    More Examples

    Example

    Insert line breaks where newlines (\n) occur, using the xhtml parameter: <?php echo nl2br("One line.\nAnother line.",false); ?> The browser output of the code above will be: One line. Another line. The HTML output of the code above will be (View Source): One line.<br> Another line. Try it Yourself » PHP String Reference PHP String Reference

    Example

    Format numbers: <?phpecho number_format("1000000")."<br>";echo number_format("1000000",2)."<br>"; echo number_format("1000000",2,",",".");?> Try it Yourself »

    Definition and Usage

    The number_format() function formats a number with grouped thousands. Note: This function supports one, two, or four parameters (not three).

    Syntax

    number_format(number,decimals,decimalpoint,separator)

    Parameter Values

    ParameterDescription
    numberRequired. The number to be formatted. If no other parameters are set, the number will be formatted without decimals and with comma (,) as the thousands separator.
    decimalsOptional. Specifies how many decimals. If this parameter is set, the number will be formatted with a dot (.) as decimal point
    decimalpointOptional. Specifies what string to use for decimal point
    separatorOptional. Specifies what string to use for thousands separator. Only the first character of separator is used. For example, "xxx" will give the same output as "x" Note: If this parameter is given, all other parameters are required as well

    Technical Details

    Return Value: Returns the formatted number
    PHP Version: 4+
    Changelog: As of PHP 5.4, this function supports multiple bytes in the parameters decimalpoint and separator. Only the first byte of each separator was used in older versions.

    More Examples

    Example

    You want to return a price: One parameter will round the number (it will be formatted without decimals). Two parameters should give the result you want: <?php$num = 1999.9;$formattedNum = number_format($num)."<br>"; echo $formattedNum;$formattedNum = number_format($num, 2);echo $formattedNum;?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Return the ASCII value of "h": <?php echo ord("h")."<br>"; echo ord("hello")."<br>"; ?> Try it Yourself »

    Definition and Usage

    The ord() function returns the ASCII value of the first character of a string.

    Syntax

    ord(string)

    Parameter Values

    ParameterDescription
    stringRequired. The string to get an ASCII value from

    Technical Details

    Return Value: Returns the ASCII value as an integer
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Parse a query string into variables: <?php parse_str("name=Peter&age=43"); echo $name."<br>"; echo $age; ?> Try it Yourself »

    Definition and Usage

    The parse_str() function parses a query string into variables. Note: If the array parameter is not set, variables set by this function will overwrite existing variables of the same name.Note: The magic_quotes_gpc setting in the php.ini file affects the output of this function. If enabled, the variables are converted by addslashes() before parsed by parse_str().

    Syntax

    parse_str(string,array)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to parse
    arrayOptional (Required from PHP 7.2). Specifies the name of an array to store the variables. This parameter indicates that the variables will be stored in an array.

    Technical Details

    Return Value: No value is returned
    PHP Version: 4+
    Changelog: PHP 7.2.0 - The array parameter is required.PHP 4.0.3 - Added the array parameter.

    More Examples

    Example

    Store the variables in an array: <?php parse_str("name=Peter&age=43",$myArray); print_r($myArray); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Write some text to the output: <?php print "Hello world!"; ?> Try it Yourself »

    Definition and Usage

    The print() function outputs one or more strings. Note: The print() function is not actually a function, so you are not required to use parentheses with it. Tip: The print() function is slightly slower than echo().

    Syntax

    print(strings)

    Parameter Values

    ParameterDescription
    stringsRequired. One or more strings to be sent to the output

    Technical Details

    Return Value: Always returns 1
    PHP Version: 4+

    More Examples

    Example

    Write the value of the string variable ($str) to the output: <?php $str = "Hello world!"; print $str; ?> Try it Yourself »

    Example

    Write the value of the string variable ($str) to the output, including HTML tags: <?php$str = "Hello world!";print $str;print "<br>What a nice day!";?> Try it Yourself »

    Example

    Join two string variables together: <?php$str1="Hello world!";$str2="What a nice day!"; print $str1 . " " . $str2;?> Try it Yourself »

    Example

    Write the value of an array to the output: <?php$age=array("Peter"=>"35");print "Peter is " . $age['Peter'] . " years old.";?> Try it Yourself »

    Example

    Write some text to the output: <?php print "This text spans multiple lines."; ?> Try it Yourself »

    Example

    Difference of single and double quotes. Single quotes will print the variable name, not the value: <?php $color = "red"; print "Roses are $color"; print "<br>"; print 'Roses are $color'; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Output a formatted string: <?php$number = 9;$str = "Beijing";printf("There are %u million bicycles in %s.",$number,$str);?> Try it Yourself »

    Definition and Usage

    The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: sprintf(), vprintf(), vsprintf(), fprintf() and vfprintf()

    Syntax

    printf(format,arg1,arg2,arg++)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    arg1Required. The argument to be inserted at the first %-sign in the format string
    arg2Optional. The argument to be inserted at the second %-sign in the format string
    arg++Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

    Technical Details

    Return Value: Returns the length of the outputted string
    PHP Version: 4+

    More Examples

    Example

    Using the format value %f: <?php $number = 123; printf("%f",$number); ?> Try it Yourself »

    Example

    Use of placeholders: <?php $number = 123; printf("With 2 decimals: %1\$.2f <br>With no decimals: %1\$u",$number); ?> Try it Yourself »

    Example

    A demonstration of all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signprintf("%%b = %b <br>",$num1); // Binary numberprintf("%%c = %c <br>",$char); // The ASCII Characterprintf("%%d = %d <br>",$num1); // Signed decimal numberprintf("%%d = %d <br>",$num2); // Signed decimal numberprintf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)printf("%%g = %g <br>",$num1); // Shorter of %e and %fprintf("%%G = %G <br>",$num1); // Shorter of %E and %fprintf("%%o = %o <br>",$num1); // Octal numberprintf("%%s = %s <br>",$num1); // Stringprintf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)printf("%%+d = %+d <br>",$num1); // Sign specifier (positive) printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)?> Try it Yourself »

    Example

    A demonstration of string specifiers: <?php$str1 = "Hello";$str2 = "Hello world!";printf("[%s]<br>",$str1); printf("[%8s]<br>",$str1);printf("[%-8s]<br>",$str1);printf("[%08s]<br>",$str1); printf("[%'*8s]<br>",$str1);printf("[%8.8s]<br>",$str2); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Decode a quoted-printable string to an 8-bit ASCII string: <?php $str = "Hello=0Aworld."; echo quoted_printable_decode($str); ?> The browser output of the code above will be: Hello world. The HTML output of the code above will be (View Source): Hello world. Try it Yourself »

    Definition and Usage

    The quoted_printable_decode() function decodes a quoted-printable string to an 8-bit ASCII string. Tip: Data encoded in quoted-printable are unlikely to be modified by mail transport. A text which is entirely US-ASCII may be encoded in quoted-printable to ensure the integrity of the data should the message pass through a character-translating, or line-wrapping gateway.

    Syntax

    quoted_printable_decode(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the quoted-printable string to be decoded

    Technical Details

    Return Value: Returns the 8-bit ASCII string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Definition and Usage

    The quoted_printable_encode() function converts an 8-bit string to a quoted-printable string. Tip: Data encoded in quoted-printable are unlikely to be modified by mail transport. A text which is entirely US-ASCII may be encoded in quoted-printable to ensure the integrity of the data should the message pass through a character-translating, or line-wrapping gateway.

    Syntax

    quoted_printable_encode(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the 8-bit string to be converted

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 5.3.0+
    PHP String Reference PHP String Reference

    Example

    Add backslashes in front of the predefined characters: <?php $str = "Hello world. (can you hear me?)"; echo quotemeta($str); ?> Try it Yourself »

    Definition and Usage

    The quotemeta() function adds backslashes in front of some predefined characters in a string. The predefined characters are:
  • period (.)
  • backslash (\)
  • plus sign (+)
  • asterisk (*)
  • question mark (?)
  • brackets ([])
  • caret (^)
  • dollar sign ($)
  • parenthesis (())
  • Tip: This function can be used to escape characters with special meanings, such as ( ), [ ], and * in SQL. Note: This function is binary-safe.

    Syntax

    quotemeta(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check

    Technical Details

    Return Value: Returns the string with meta characters quoted
    PHP Version: 4+

    More Examples

    Example

    Add backslashes in front of many predefined characters: <?php$str1 = "1 + 1 = 2";$str2 = "1 * 1 = 1";$str3 = "Could you borrow me 5$?";$str4 = "Are you not entertained? (I am..)";$str5 = "The caret [ ^ ] Looks like a hat!";echo quotemeta($str1)."<br>"; echo quotemeta($str2)."<br>";echo quotemeta($str3)."<br>";echo quotemeta($str4)."<br>";echo quotemeta($str5)."<br>";?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Remove characters from the right side of a string: <?php $str = "Hello World!"; echo $str . "<br>"; echo rtrim($str,"World!"); ?> Try it Yourself »

    Definition and Usage

    The rtrim() function removes whitespace or other predefined characters from the right side of a string. Related functions:
  • ltrim() - Removes whitespace or other predefined characters from the left side of a string
  • trim() - Removes whitespace or other predefined characters from both sides of a string
  • Syntax

    rtrim(string,charlist)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    charlistOptional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
  • "\0" - NULL
  • "\t" - tab
  • "\n" - new line
  • "\x0B" - vertical tab
  • "\r" - carriage return
  • " " - ordinary white space
  • Technical Details

    Return Value: Returns the modified string
    PHP Version: 4+
    Changelog: The charlist parameter was added in PHP 4.1

    More Examples

    Example

    Remove whitespaces from the right side of a string: <?php $str = "Hello World! "; echo "Without rtrim: " . $str; echo "<br>"; echo "With rtrim: " . rtrim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without rtrim: Hello World! <br>With rtrim: Hello World! </body> </html> The browser output of the code above will be: Without rtrim: Hello World! With rtrim: Hello World! Try it Yourself »

    Example

    Remove newlines (\n) from the right side of a string: <?php $str = "Hello World!\n\n\n"; echo "Without rtrim: " . $str; echo "<br>"; echo "With rtrim: " . rtrim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without rtrim: Hello World! <br>With rtrim: Hello World! </body> </html> The browser output of the code above will be: Without rtrim: Hello World! With rtrim: Hello World! Try it Yourself » PHP String Reference PHP String Reference

    Example

    Set the locale to US English and then back to default again: <?php echo setlocale(LC_ALL,"US"); echo "<br>"; echo setlocale(LC_ALL,NULL); ?> Try it Yourself »

    Definition and Usage

    The setlocale() function sets locale information. Locale information is language, monetary, time and other information specific for a geographical area. Note: The setlocale() function changes the locale only for the current script. Tip: The locale information can be set to system default with setlocale(LC_ALL,NULL) Tip: To get numeric formatting information, see the localeconv() function.

    Syntax

    setlocale(constant,location)

    Parameter Values

    ParameterDescription
    constantRequired. Specifies what locale information should be set. Available constants:
  • LC_ALL - All of the below
  • LC_COLLATE - Sort order
  • LC_CTYPE - Character classification and conversion (e.g. all characters should be lower or upper-case)
  • LC_MESSAGES - System message formatting
  • LC_MONETARY - Monetary/currency formatting
  • LC_NUMERIC - Numeric formatting
  • LC_TIME - Date and time formatting
  • locationRequired. Specifies what country/region to set the locale information to. Can be a string or an array. It is possible to pass multiple locations.If the location is NULL or the empty string ", the location names will be set from the values of environment variables with the same names as the constants above, or from "LANG".If the location is "0", the location setting is not affected, only the current setting is returned.If the location is an array, setlocale() will try each array element until it finds a valid language or region code. This is very useful if a region is known under different names on different systems.Note: To view all available language codes, go to our Language code reference.

    Technical Details

    Return Value: Returns the current locale settings, or FALSE on failure. The return value depends on the system that PHP is running.
    PHP Version: 4+
    Changelog: PHP 5.3.0 - If a string is passed to the constant parameter instead of one of the LC_ constants, this function throws an E_DREPRECATED notice.
    PHP String Reference PHP String Reference

    Example

    Calculate the SHA-1 hash of the string "Hello": <?php $str = "Hello"; echo sha1($str); ?> Try it Yourself »

    Definition and Usage

    The sha1() function calculates the SHA-1 hash of a string. The sha1() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature." Tip: To calculate the SHA-1 hash of a file, use the sha1_file() function.

    Syntax

    sha1(string,raw)

    Parameter Values

    ParameterDescription
    stringRequired. The string to be calculated
    rawOptional. Specify hex or binary output format:
  • TRUE - Raw 20 character binary format
  • FALSE - Default. 40 character hex number
  • Technical Details

    Return Value: Returns the calculated SHA-1 hash on success, or FALSE on failure
    PHP Version: 4.3.0+

    More Examples

    Example

    Print the result of sha1(): <?php $str = "Hello"; echo "The string: ".$str."<br>"; echo "TRUE - Raw 20 character binary format: ".sha1($str, TRUE)."<br>"; echo "FALSE - 40 character hex number: ".sha1($str)."<br>"; ?> Try it Yourself »

    Example

    Print the result of sha1() and then test it: <?php$str = "Hello";echo sha1($str);if (sha1($str) == "f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0") { echo "<br>Hello world!"; exit; }?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Calculate the SHA-1 hash of the text file "test.txt": <?php $filename = "test.txt"; $sha1file = sha1_file($filename); echo $sha1file; ?> The output of the code above will be: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

    Definition and Usage

    The sha1_file() function calculates the SHA-1 hash of a file. The sha1_file() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature." This function returns the calculated SHA-1 hash on success, or FALSE on failure.

    Syntax

    sha1_file(file,raw)

    Parameter Values

    ParameterDescription
    fileRequired. The file to be calculated
    rawOptional. A boolean value that specifies hex or binary output format:
  • TRUE - Raw 20 character binary format
  • FALSE - Default. 40 character hex number
  • Technical Details

    Return Value: Returns the calculated SHA-1 hash on success, or FALSE on failure
    PHP Version: 4.3.0+
    Changelog: As of PHP 5.1, it is possible to use sha1_file() with wrappers, e.g. sha1_file("https://w3schools.com/..")

    More Examples

    Example

    Store the SHA-1 hash of "test.txt" in a file: <?php $sha1file = sha1_file("test.txt"); file_put_contents("sha1file.txt",$sha1file); ?> Test if "test.txt" has been changed (that is if the SHA-1 hash has been changed): <?php $sha1file = file_get_contents("sha1file.txt"); if (sha1_file("test.txt") == $sha1file) { echo "The file is ok."; } else { echo "The file has been changed."; } ?> The output of the code above could be: The file is ok. PHP String Reference PHP String Reference

    Example

    Calculate the similarity between two strings and return the matching characters: <?php echo similar_text("Hello World","Hello Peter"); ?> Try it Yourself »

    Definition and Usage

    The similar_text() function calculates the similarity between two strings. It can also calculate the similarity of the two strings in percent. Note: The levenshtein() function is faster than the similar_text() function. However, the similar_text() function will give you a more accurate result with less modifications needed.

    Syntax

    similar_text(string1,string2,percent)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to be compared
    string2Required. Specifies the second string to be compared
    percentOptional. Specifies a variable name for storing the similarity in percent

    Technical Details

    Return Value: Returns the number of matching characters of two strings
    PHP Version: 4+

    More Examples

    Example

    Calculate the similarity between two strings in percent: <?php similar_text("Hello World","Hello Peter",$percent); echo $percent; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Calculate the soundex key of "Hello": <?php $str = "Hello"; echo soundex($str); ?> Try it Yourself »

    Definition and Usage

    The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. The soundex() function can be used for spelling applications. Note: The soundex() function creates the same key for similar sounding words. Tip: metaphone() is more accurate than soundex(), because metaphone() knows the basic rules of English pronunciation.

    Syntax

    soundex(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check

    Technical Details

    Return Value: Returns the soundex key of the string on success, or FALSE on failure.
    PHP Version: 4+

    More Examples

    Example

    Using the soundex() function on two similar sounding words: <?php $str = "Assistance"; $str2 = "Assistants"; echo soundex($str); echo "<br>"; echo soundex($str2); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Replace the percent (%) sign by a variable passed as an argument: <?php$number = 9;$str = "Beijing";$txt = sprintf("There are %u million bicycles in %s.",$number,$str);echo $txt;?> Try it Yourself »

    Definition and Usage

    The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: printf(), vprintf(), vsprintf(), fprintf() and vfprintf()

    Syntax

    sprintf(format,arg1,arg2,arg++)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    arg1Required. The argument to be inserted at the first %-sign in the format string
    arg2Optional. The argument to be inserted at the second %-sign in the format string
    arg++Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

    Technical Details

    Return Value: Returns the formatted string
    PHP Version: 4+

    More Examples

    Example

    Using the format value %f: <?php $number = 123; $txt = sprintf("%f",$number); echo $txt; ?> Try it Yourself »

    Example

    Use of placeholders: <?php $number = 123; $txt = sprintf("With 2 decimals: %1\$.2f <br>With no decimals: %1\$u",$number); echo $txt; ?> Try it Yourself »

    Example

    A demonstration of all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signecho sprintf("%%b = %b",$num1)."<br>"; // Binary numberecho sprintf("%%c = %c",$char)."<br>"; // The ASCII Character echo sprintf("%%d = %d",$num1)."<br>"; // Signed decimal numberecho sprintf("%%d = %d",$num2)."<br>"; // Signed decimal numberecho sprintf("%%e = %e",$num1)."<br>"; // Scientific notation (lowercase)echo sprintf("%%E = %E",$num1)."<br>"; // Scientific notation (uppercase)echo sprintf("%%u = %u",$num1)."<br>"; // Unsigned decimal number (positive) echo sprintf("%%u = %u",$num2)."<br>"; // Unsigned decimal number (negative) echo sprintf("%%f = %f",$num1)."<br>"; // Floating-point number (local settings aware)echo sprintf("%%F = %F",$num1)."<br>"; // Floating-point number (not local sett aware)echo sprintf("%%g = %g",$num1)."<br>"; // Shorter of %e and %fecho sprintf("%%G = %G",$num1)."<br>"; // Shorter of %E and %fecho sprintf("%%o = %o",$num1)."<br>"; // Octal number echo sprintf("%%s = %s",$num1)."<br>"; // Stringecho sprintf("%%x = %x",$num1)."<br>"; // Hexadecimal number (lowercase)echo sprintf("%%X = %X",$num1)."<br>"; // Hexadecimal number (uppercase)echo sprintf("%%+d = %+d",$num1)."<br>"; // Sign specifier (positive)echo sprintf("%%+d = %+d",$num2)."<br>"; // Sign specifier (negative)?> Try it Yourself »

    Example

    A demonstration of string specifiers: <?php$str1 = "Hello";$str2 = "Hello world!";echo sprintf("[%s]",$str1)."<br>"; echo sprintf("[%8s]",$str1)."<br>";echo sprintf("[%-8s]",$str1)."<br>"; echo sprintf("[%08s]",$str1)."<br>"; echo sprintf("[%'*8s]",$str1)."<br>";echo sprintf("[%8.8s]",$str2)."<br>"; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Parse a string: <?php $str = "age:30 weight:60kg"; sscanf($str,"age:%d weight:%dkg",$age,$weight); // show types and values var_dump($age,$weight); ?> Try it Yourself » The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into variables based on the format string. If only two parameters are passed to this function, the data will be returned as an array. Otherwise, if optional parameters are passed, the data parsed are stored in them. If there are more specifiers than variables to contain them, an error occurs. However, if there are less specifiers than variables, the extra variables contain NULL. Related functions:
  • printf() - outputs a formatted string
  • sprintf() - writes a formatted string to a variable
  • Syntax

    sscanf(string,format,arg1,arg2,arg++)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to read
    formatRequired. Specifies the format to use.Possible format values:
  • %% - Returns a percent sign
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    arg1Optional. The first variable to store data in
    arg2Optional. The second variable to store data in
    arg++Optional. The third, fourth, and so on, to store data in

    Technical Details

    Return Value: If only two parameters are passed to this function, the data will be returned as an array. Otherwise, if optional parameters are passed, the data parsed are stored in them. If there are more specifiers than variables to contain them, an error occurs. However, if there are less specifiers than variables, the extra variables contain NULL.
    PHP Version: 4.0.1+

    More Examples

    Example

    Using the format values %s, %d and %c: <?php$str = "If you divide 4 by 2 you'll get 2";$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");print_r($format);?> Try it Yourself » PHP String Reference PHP String Reference

    Definition and Usage

    The str_getcsv() function parses a string for fields in CSV format and returns an array containing the fields read.

    Syntax

    str_getcsv(string,separator,enclosure,escape)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to parse
    separatorOptional. A character that specifies the field separator. Default is comma ( , )
    enclosureOptional. A character that specifies the field enclosure character. Default is "
    escapeOptional. A character that specifies the escape character. Default is backslash (\)

    Technical Details

    Return Value: Returns the CSV fields in an array
    PHP Version: 5.3.0+
    PHP String Reference PHP String Reference

    Example

    Replace the characters "WORLD" (case-insensitive) in the string "Hello world!" with "Peter": <?php echo str_ireplace("WORLD","Peter","Hello world!"); ?> Try it Yourself »

    Definition and Usage

    The str_ireplace() function replaces some characters with some other characters in a string. This function works by the following rules:
  • If the string to be searched is an array, it returns an array
  • If the string to be searched is an array, find and replace is performed with every array element
  • If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
  • If find is an array and replace is a string, the replace string will be used for every find value
  • Note: This function is case-insensitive. Use the str_replace() function to perform a case-sensitive search. Note: This function is binary-safe.

    Syntax

    str_ireplace(find,replace,string,count)

    Parameter Values

    ParameterDescription
    findRequired. Specifies the value to find
    replaceRequired. Specifies the value to replace the value in find
    stringRequired. Specifies the string to be searched
    countOptional. A variable that counts the number of replacements

    Technical Details

    Return Value: Returns a string or an array with the replaced values
    PHP Version: 5+
    Changelog: The count parameter was added in PHP 5.0

    More Examples

    Example

    Using str_ireplace() with an array and a count variable: <?php $arr = array("blue","red","green","yellow"); print_r(str_ireplace("RED","pink",$arr,$i)); // This function is case-insensitive echo "Replacements: $i"; ?> Try it Yourself »

    Example

    Using str_ireplace() with fewer elements in replace than find: <?php $find = array("HELLO","WORLD"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_ireplace($find,$replace,$arr)); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Pad to the right side of the string, to a new length of 20 characters: <?php $str = "Hello World"; echo str_pad($str,20,"."); ?> Try it Yourself »

    Definition and Usage

    The str_pad() function pads a string to a new length.

    Syntax

    str_pad(string,length,pad_string,pad_type)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to pad
    lengthRequired. Specifies the new string length. If this value is less than the original length of the string, nothing will be done
    pad_stringOptional. Specifies the string to use for padding. Default is whitespace
    pad_typeOptional. Specifies what side to pad the string.Possible values:
  • STR_PAD_BOTH - Pad to both sides of the string. If not an even number, the right side gets the extra padding
  • STR_PAD_LEFT - Pad to the left side of the string
  • STR_PAD_RIGHT - Pad to the right side of the string. This is default
  • Technical Details

    Return Value: Returns the padded string
    PHP Version: 4.0.1+

    More Examples

    Example

    Pad to the left side of the string: <?php $str = "Hello World"; echo str_pad($str,20,".",STR_PAD_LEFT); ?> Try it Yourself »

    Example

    Pad to both sides of the string: <?php $str = "Hello World"; echo str_pad($str,20,".:",STR_PAD_BOTH); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Repeat the string "Wow" 13 times: <?php echo str_repeat("Wow",13); ?> Try it Yourself »

    Definition and Usage

    The str_repeat() function repeats a string a specified number of times.

    Syntax

    str_repeat(string,repeat)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to repeat
    repeatRequired. Specifies the number of times the string will be repeated. Must be greater or equal to 0

    Technical Details

    Return Value: Returns the repeated string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Replace the characters "world" in the string "Hello world!" with "Peter": <?php echo str_replace("world","Peter","Hello world!"); ?> Try it Yourself »

    Definition and Usage

    The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules:
  • If the string to be searched is an array, it returns an array
  • If the string to be searched is an array, find and replace is performed with every array element
  • If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
  • If find is an array and replace is a string, the replace string will be used for every find value
  • Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search. Note: This function is binary-safe.

    Syntax

    str_replace(find,replace,string,count)

    Parameter Values

    ParameterDescription
    findRequired. Specifies the value to find
    replaceRequired. Specifies the value to replace the value in find
    stringRequired. Specifies the string to be searched
    countOptional. A variable that counts the number of replacements

    Technical Details

    Return Value: Returns a string or an array with the replaced values
    PHP Version: 4+
    Changelog: The count parameter was added in PHP 5.0Before PHP 4.3.3, this function experienced trouble when using arrays as both find and replace parameters, which caused empty find indexes to be skipped without advancing the internal pointer on the replace array. Newer versions will not have this problem.As of PHP 4.0.5, most of the parameters can now be an array

    More Examples

    Example

    Using str_replace() with an array and a count variable: <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?> Try it Yourself »

    Example

    Using str_replace() with fewer elements in replace than find: <?php $find = array("Hello","world"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_replace($find,$replace,$arr)); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Encode and decode a string: <?php echo str_rot13("Hello World"); echo "<br>"; echo str_rot13("Uryyb Jbeyq"); ?> Try it Yourself »

    Definition and Usage

    The str_rot13() function performs the ROT13 encoding on a string. The ROT13 encoding shifts every letter 13 places in the alphabet. Numeric and non-alphabetical characters remains untouched. Tip: Encoding and decoding are done by the same function. If you pass an encoded string as argument, the original string will be returned.

    Syntax

    str_rot13(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to encode

    Technical Details

    Return Value: Returns the ROT13 version of the encoded string
    PHP Version: 4.2.0+
    PHP String Reference PHP String Reference

    Example

    Randomly shuffle all characters of a string: <?php echo str_shuffle("Hello World"); ?> Try it Yourself »

    Definition and Usage

    The str_shuffle() function randomly shuffles all the characters of a string.

    Syntax

    str_shuffle(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to shuffle

    Technical Details

    Return Value: Returns the shuffled string
    PHP Version: 4.3.0+
    PHP String Reference PHP String Reference

    Example

    Split the string "Hello" into an array: <?php print_r(str_split("Hello")); ?> Try it Yourself »

    Definition and Usage

    The str_split() function splits a string into an array.

    Syntax

    str_split(string,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to split
    lengthOptional. Specifies the length of each array element. Default is 1

    Technical Details

    Return Value: If length is less than 1, the str_split() function will return FALSE. If length is larger than the length of string, the entire string will be returned as the only element of the array.
    PHP Version: 5+

    More Examples

    Example

    Using the length parameter: <?php print_r(str_split("Hello",3)); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Count the number of words found in the string "Hello World!": <?php echo str_word_count("Hello world!"); ?> Try it Yourself »

    Definition and Usage

    The str_word_count() function counts the number of words in a string.

    Syntax

    str_word_count(string,return,char)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    returnOptional. Specifies the return value of the str_word_count() function.Possible values:
  • 0 - Default. Returns the number of words found
  • 1 - Returns an array with the words from the string
  • 2 - Returns an array where the key is the position of the word in the string, and value is the actual word
  • charOptional. Specifies special characters to be considered as words.

    Technical Details

    Return Value: Returns a number or an array, depending on the chosen return parameter
    PHP Version: 4.3.0+
    Changelog: The char parameter was added in PHP 5.1

    More Examples

    Example

    Return an array with the words from the string: <?php print_r(str_word_count("Hello world!",1)); ?> Try it Yourself »

    Example

    Return an array where the key is the position of the word in the string, and value is the actual word: <?php print_r(str_word_count("Hello world!",2)); ?> Try it Yourself »

    Example

    Without and with the char parameter: <?php print_r(str_word_count("Hello world & good morning!",1)); print_r(str_word_count("Hello world & good morning!",1,"&")); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings (case-insensitive): <?php echo strcasecmp("Hello world!","HELLO WORLD!"); ?> Try it Yourself »

    Definition and Usage

    The strcasecmp() function compares two strings. Tip: The strcasecmp() function is binary-safe and case-insensitive. Tip: This function is similar to the strncasecmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncasecmp().

    Syntax

    strcasecmp(string1,string2)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4+

    More Examples

    Example

    Compare two strings (case-insensitive = HELLO and hELLo will output the same): <?php echo strcasecmp("Hello","HELLO");echo "<br>";echo strcasecmp("Hello","hELLo"); ?> Try it Yourself »

    Example

    Different return values: <?php echo strcasecmp("Hello world!","HELLO WORLD!"); // The two strings are equal echo strcasecmp("Hello world!","HELLO"); // String1 is greater than string2 echo strcasecmp("Hello world!","HELLO WORLD! HELLO!"); // String1 is less than string2 ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Find the first occurrence of "world" inside "Hello world!" and return the rest of the string: <?php echo strchr("Hello world!","world"); ?> Try it Yourself »

    Definition and Usage

    The strchr() function searches for the first occurrence of a string inside another string. This function is an alias of the strstr() function. Note: This function is binary-safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.

    Syntax

    strchr(string,search,before_search);

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    searchRequired. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number
    before_searchOptional. A boolean value whose default is "false". If set to "true", it returns the part of the string before the first occurrence of the search parameter.

    Technical Details

    Return Value: Returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
    PHP Version: 4+
    Changelog: The before_search parameter was added in PHP 5.3

    More Examples

    Example

    Search a string for the ASCII value of "o" and return the rest of the string: <?php echo strchr("Hello world!",111); ?> Try it Yourself »

    Example

    Return the part of the string before the first occurence of "world": <?php echo strchr("Hello world!","world",true); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings (case-sensitive): <?php echo strcmp("Hello world!","Hello world!"); ?> Try it Yourself »

    Definition and Usage

    The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

    Syntax

    strcmp(string1,string2)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4+

    More Examples

    Example

    Compare two strings (case-sensitive = Hello and hELLo will not output the same): <?phpecho strcmp("Hello","Hello");echo "<br>";echo strcmp("Hello","hELLo"); ?> Try it Yourself »

    Example

    Different return values: <?php echo strcmp("Hello world!","Hello world!"); // the two strings are equal echo strcmp("Hello world!","Hello"); // string1 is greater than string2 echo strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string2 ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare strings: <?php setlocale (LC_COLLATE, 'NL'); echo strcoll("Hello World!","Hello World!"); echo "<br>"; setlocale (LC_COLLATE, 'en_US'); echo strcoll("Hello World!","Hello World!"); ?> Try it Yourself »

    Definition and Usage

    The strcoll() function compares two strings. The comparison of the strings may vary depending on the locale settings (A<a or A>a). Note: The strcoll() is case-sensitive but not binary-safe. Note: If the current locale is C or POSIX, this function works the same way as strcmp().

    Syntax

    strcoll(string1,string2)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4.0.5+
    PHP String Reference PHP String Reference

    Example

    Print the number of characters found in "Hello world!" before the character "w": <?php echo strcspn("Hello world!","w"); ?> Try it Yourself »

    Definition and Usage

    The strcspn() function returns the number of characters (including whitespaces) found in a string before any part of the specified characters are found. Tip: Use the strspn() function to the number of characters found in the string that contains only characters from a specified character list. Note: This function is binary-safe.

    Syntax

    strcspn(string,char,start,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    charRequired. Specifies the characters to search for
    startOptional. Specifies where in string to start
    lengthOptional. Specifies the length of the string (how much of the string to search)

    Technical Details

    Return Value: Returns the number of characters found in a string before any part of the specified characters are found
    PHP Version: 4+
    Changelog: The start and length parameters were added in PHP 4.3

    More Examples

    Example

    Using all parameters to print the number of characters found in "Hello world!" before the character "w": <?php echo strcspn("Hello world!","w",0,6); // The start position is 0 and the length of the search string is 6. ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Strip the string from HTML tags: <?php echo strip_tags("Hello <b>world!</b>"); ?> Try it Yourself »

    Definition and Usage

    The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.

    Syntax

    strip_tags(string,allow)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    allowOptional. Specifies allowable tags. These tags will not be removed

    Technical Details

    Return Value: Returns the stripped string
    PHP Version: 4+
    Changelog: As of PHP 5.3.4, this function ignores self-closing XHTML tags (like <br />) in allow parameterAs of PHP 5.0, this function is binary-safe.As of PHP 4.3, HTML comments are always stripped.

    More Examples

    Example

    Strip the string from HTML tags, but allow <b> tags to be used: <?php echo strip_tags("Hello <b><i>world!</i></b>","<b>"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Remove the backslash in front of "World!": <?php echo stripcslashes("Hello \World!"); ?> Try it Yourself »

    Definition and Usage

    The stripcslashes() function removes backslashes added by the addcslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

    Syntax

    stripcslashes(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check

    Technical Details

    Return Value: Returns the unescaped string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Remove the backslash: <?php echo stripslashes("Who\'s Peter Griffin?"); ?> Try it Yourself »

    Definition and Usage

    The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

    Syntax

    stripslashes(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check

    Technical Details

    Return Value: Returns a string with backslashes stripped off
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Find the position of the first occurrence of "php" inside the string: <?php echo stripos("I love php, I love php too!","PHP"); ?> Try it Yourself »

    Definition and Usage

    The stripos() function finds the position of the first occurrence of a string inside another string. Note: The stripos() function is case-insensitive. Note: This function is binary-safe. Related functions:
  • strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
  • strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
  • strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
  • Syntax

    stripos(string,find,start)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    findRequired. Specifies the string to find
    startOptional. Specifies where to begin the search

    Technical Details

    Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found. Note: String positions start at 0, and not 1.
    PHP Version: 5+
    PHP String Reference PHP String Reference

    Example

    Find the first occurrence of "world" inside "Hello world!", and return the rest of the string: <?php echo stristr("Hello world!","WORLD"); ?> Try it Yourself »

    Definition and Usage

    The stristr() function searches for the first occurrence of a string inside another string. Note: This function is binary-safe. Note: This function is case-insensitive. For a case-sensitive search, use strstr() function.

    Syntax

    stristr(string,search,before_search)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    searchRequired. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number
    before_searchOptional. A boolean value whose default is "false". If set to "true", it returns the part of the string before the first occurrence of the search parameter.

    Technical Details

    Return Value: Returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
    PHP Version: 4+
    Changelog: The before_search parameter was added in PHP 5.3.This function was made binary-safe in PHP 4.3

    More Examples

    Example

    Search a string for the ASCII value of "o", and return the rest of the string: <?php echo stristr("Hello world!",111); ?> Try it Yourself »

    Example

    Return the part of the string before the first occurence of "world": <?php echo stristr("Hello world!","WORLD",true); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Return the length of the string "Hello": <?phpecho strlen("Hello");?> Try it Yourself »

    Definition and Usage

    The strlen() function returns the length of a string.

    Syntax

    strlen(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check

    Technical Details

    Return Value: Returns the length of a string (in bytes) on success, and 0 if the string is empty
    PHP Version: 4+

    More Examples

    Example

    Return the length of the string "Hello World": <?php echo strlen("Hello world!"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings using a "natural" algorithm (case-insensitive): <?php echo strnatcasecmp("2Hello world!","10Hello WORLD!"); echo "<br>"; echo strnatcasecmp("10Hello world!","2Hello WORLD!"); ?> Try it Yourself »

    Definition and Usage

    The strnatcasecmp() function compares two strings using a "natural" algorithm. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2. Note: The strnatcasecmp() is case-insensitive.

    Syntax

    strnatcasecmp(string1,string2)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4+

    More Examples

    Example

    Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp): <?php$arr1 = $arr2 = array("pic1","pic2","pic10","pic01","pic100","pic20","pic30","pic200"); echo "Standard string comparison"."<br>";usort($arr1,"strcmp"); print_r($arr1);echo "<br>";echo "Natural order string comparison"."<br>";usort($arr2,"strnatcmp");print_r($arr2); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings using a "natural" algorithm (case-sensitive): <?php echo strnatcmp("2Hello world!","10Hello world!"); echo "<br>"; echo strnatcmp("10Hello world!","2Hello world!"); ?> Try it Yourself »

    Definition and Usage

    The strnatcmp() function compares two strings using a "natural" algorithm. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2. Note: This function is case-sensitive.

    Syntax

    strnatcmp(string1,string2)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4+

    More Examples

    Example

    Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp): <?php$arr1 = $arr2 = array("pic1","pic2","pic10","pic01","pic100","pic20","pic30","pic200"); echo "Standard string comparison"."<br>";usort($arr1,"strcmp"); print_r($arr1);echo "<br>";echo "Natural order string comparison"."<br>";usort($arr2,"strnatcmp");print_r($arr2); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings (case-insensitive): <?php echo strncasecmp("Hello world!","hello earth!",6); ?> Try it Yourself »

    Definition and Usage

    The strncasecmp() function compares two strings. Note: The strncasecmp() is binary-safe and case-insensitive. Tip: This function is similar to the strcasecmp() function, except that strcasecmp() does not have the length parameter.

    Syntax

    strncasecmp(string1,string2,length)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare
    lengthRequired. Specify the number of characters from each string to be used in the comparison

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4.0.2+

    More Examples

    Example

    Compare two strings (case-insensitive = Hello and hELLo will output the same): <?phpecho strncasecmp("Hello","Hello",6);echo "<br>";echo strncasecmp("Hello","hELLo",6); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings (case-sensitive): <?php echo strncmp("Hello world!","Hello earth!",6); ?> Try it Yourself »

    Definition and Usage

    The strncmp() function compares two strings. Note: The strncmp() is binary-safe and case-sensitive. Tip: This function is similar to the strcmp() function, except that strcmp() does not have the length parameter.

    Syntax

    strncmp(string1,string2,length)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare
    lengthRequired. Specify the number of characters from each string to be used in the comparison

    Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2
  • PHP Version: 4+

    More Examples

    Example

    Compare two strings (case-sensitive = Hello and hELLo will not output the same): <?phpecho strncmp("Hello","Hello",6);echo "<br>";echo strncmp("Hello","hELLo",6); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Search a string for the characters "oe", and return the rest of the string from where it found the first occurrence of the specified characters: <?php echo strpbrk("Hello world!","oe"); ?> Try it Yourself »

    Definition and Usage

    The strpbrk() function searches a string for any of the specified characters. Note: This function is case-sensitive. This function returns the rest of the string from where it found the first occurrence of a specified character, otherwise it returns FALSE.

    Syntax

    strpbrk(string,charlist)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    charlistRequired. Specifies the characters to find

    Technical Details

    Return Value: Returns the string starting from the character found, otherwise it returns FALSE
    PHP Version: 5+

    More Examples

    Example

    This function is case-sensitive ("W" and "w" will not output the same): <?php echo strpbrk("Hello world!","W");echo "<br>";echo strpbrk("Hello world!","w"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Find the position of the first occurrence of "php" inside the string: <?php echo strpos("I love php, I love php too!","php"); ?> Try it Yourself »

    Definition and Usage

    The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive. Note: This function is binary-safe. Related functions:
  • strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
  • stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)
  • strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
  • Syntax

    strpos(string,find,start)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    findRequired. Specifies the string to find
    startOptional. Specifies where to begin the search. If start is a negative number, it counts from the end of the string.

    Technical Details

    Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found. Note: String positions start at 0, and not 1.
    PHP Version: 4+
    Changelog: PHP 7.1.0 - The start parameter can be a negative number
    PHP String Reference PHP String Reference

    Example

    Search a string for "world", and return all characters from this position to the end of the string: <?php echo strrchr("Hello world!","world"); ?> Try it Yourself »

    Definition and Usage

    The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string. Note: This function is binary-safe.

    Syntax

    strrchr(string,char)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    charRequired. Specifies the string to find. If this is a number, it will search for the character matching the ASCII value of that number

    Technical Details

    Return Value: Returns all characters from the last occurrence of a string within another string, to the end of the main string, or FALSE if the character is not found
    PHP Version: 4+
    Changelog: This function was made binary-safe in PHP 4.3

    More Examples

    Example

    Search a string for "What", and return all characters from this position to the end of the string: <?php echo strrchr("Hello world! What a beautiful day!", "What"); ?> Try it Yourself »

    Example

    Search a string for the ASCII value of "e" (101) and return all characters from this position to the end of the string: <?php echo strrchr("Hello world!",101); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Reverse the string "Hello World!": <?php echo strrev("Hello World!"); ?> Try it Yourself »

    Definition and Usage

    The strrev() function reverses a string.

    Syntax

    strrev(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to reverse

    Technical Details

    Return Value: Returns the reversed string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Find the position of the last occurrence of "php" inside the string: <?php echo strripos("I love php, I love php too!","PHP"); ?> Try it Yourself »

    Definition and Usage

    The strripos() function finds the position of the last occurrence of a string inside another string. Note: The strripos() function is case-insensitive. Related functions:
  • stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)
  • strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
  • strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
  • Syntax

    strripos(string,find,start)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    findRequired. Specifies the string to find
    startOptional. Specifies where to begin the search

    Technical Details

    Return Value: Returns the position of the last occurrence of a string inside another string, or FALSE if the string is not found. Note: String positions start at 0, and not 1.
    PHP Version: 5+
    Changelog: As of PHP 5.0, the find parameter may now be a string of more than one character.The start parameter was added in PHP 5.0
    PHP String Reference PHP String Reference

    Example

    Find the position of the last occurrence of "php" inside the string: <?php echo strrpos("I love php, I love php too!","php"); ?> Try it Yourself »

    Definition and Usage

    The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions:
  • strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
  • stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)
  • strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
  • Syntax

    strrpos(string,find,start)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    findRequired. Specifies the string to find
    startOptional. Specifies where to begin the search

    Technical Details

    Return Value: Returns the position of the last occurrence of a string inside another string, or FALSE if the string is not found. Note: String positions start at 0, and not 1.
    PHP Version: 4+
    Changelog: As of PHP 5.0, the find parameter may now be a string of more than one characterThe start parameter was added in PHP 5.0
    PHP String Reference PHP String Reference

    Example

    Return the number of characters found in the string "Hello world!" that contains the characters "kHlleo": <?php echo strspn("Hello world!","kHlleo"); ?> Try it Yourself »

    Definition and Usage

    The strspn() function returns the number of characters found in the string that contains only characters from the charlist parameter. Tip: Use the strcspn() function to return the number of characters found in a string before any part of the specified characters are found. Note: This function is binary-safe.

    Syntax

    strspn(string,charlist,start,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    charlistRequired. Specifies the characters to find
    startOptional. Specifies where in the string to start
    lengthOptional. Defines the length of the string

    Technical Details

    Return Value: Returns the number of characters found in the string that contains only characters from the charlist parameter.
    PHP Version: 4+
    Changelog: The start and length parameters were added in PHP 4.3.

    More Examples

    Example

    Return the number of characters found in the string "abcdefand" that contains the characters "abc": <?php echo strspn("abcdefand","abc"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Find the first occurrence of "world" inside "Hello world!" and return the rest of the string: <?php echo strstr("Hello world!","world"); ?> Try it Yourself »

    Definition and Usage

    The strstr() function searches for the first occurrence of a string inside another string. Note: This function is binary-safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.

    Syntax

    strstr(string,search,before_search)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to search
    searchRequired. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number
    before_searchOptional. A boolean value whose default is "false". If set to "true", it returns the part of the string before the first occurrence of the search parameter.

    Technical Details

    Return Value: Returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
    PHP Version: 4+
    Changelog: The before_search parameter was added in PHP 5.3

    More Examples

    Example

    Search a string for the ASCII value of "o" and return the rest of the string: <?php echo strstr("Hello world!",111); ?> Try it Yourself »

    Example

    Return the part of the string before the first occurence of "world": <?php echo strstr("Hello world!","world",true); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Split string one by one: In the example below, note that it is only the first call to strtok() that uses the string argument. After the first call, this function only needs the split argument, as it keeps track of where it is in the current string. To tokenize a new string, call strtok() with the string argument again: <?php$string = "Hello world. Beautiful day today.";$token = strtok($string, " ");while ($token !== false){echo "$token<br>"; $token = strtok(" ");} ?> Try it Yourself »

    Definition and Usage

    The strtok() function splits a string into smaller strings (tokens).

    Syntax

    strtok(string,split)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to split
    splitRequired. Specifies one or more split characters

    Technical Details

    Return Value: Returns a string token
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Convert all characters to lowercase: <?php echo strtolower("Hello WORLD."); ?> Try it Yourself »

    Definition and Usage

    The strtolower() function converts a string to lowercase. Note: This function is binary-safe. Related functions:
  • strtoupper() - converts a string to uppercase
  • lcfirst() - converts the first character of a string to lowercase
  • ucfirst() - converts the first character of a string to uppercase
  • ucwords() - converts the first character of each word in a string to uppercase
  • Syntax

    strtolower(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert

    Technical Details

    Return Value: Returns the the lowercased string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Convert all characters to uppercase: <?php echo strtoupper("Hello WORLD!"); ?> Try it Yourself »

    Definition and Usage

    The strtoupper() function converts a string to uppercase. Note: This function is binary-safe. Related functions:
  • strtolower() - converts a string to lowercase
  • lcfirst() - converts the first character of a string to lowercase
  • ucfirst() - converts the first character of a string to uppercase
  • ucwords() - converts the first character of each word in a string to uppercase
  • Syntax

    strtoupper(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert

    Technical Details

    Return Value: Returns the the uppercased string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Replace the characters "ia" in the string with "eo": <?php echo strtr("Hilla Warld","ia","eo"); ?> Try it Yourself »

    Definition and Usage

    The strtr() function translates certain characters in a string. Note: If the from and to parameters are different in length, both will be formatted to the length of the shortest.

    Syntax

    strtr(string,from,to) or strtr(string,array)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to translate
    fromRequired (unless array is used). Specifies what characters to change
    toRequired (unless array is used). Specifies what characters to change into
    arrayRequired (unless to and from is used). An array containing what to change from as key, and what to change to as value

    Technical Details

    Return Value: Returns the translated string. If the array parameter contains a key which is an empty string ("), it will return FALSE.
    PHP Version: 4+

    More Examples

    Example

    Replace the string "Hello world" with "Hi earth": <?php $arr = array("Hello" => "Hi", "world" => "earth"); echo strtr("Hello world",$arr); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Return "world" from the string: <?php echo substr("Hello world",6); ?> Try it Yourself »

    Definition and Usage

    The substr() function returns a part of a string.

    Syntax

    substr(string,start,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to return a part of
    startRequired. Specifies where to start in the string
  • A positive number - Start at a specified position in the string
  • A negative number - Start at a specified position from the end of the string
  • 0 - Start at the first character in string
  • lengthOptional. Specifies the length of the returned string. Default is to the end of the string.
  • A positive number - The length to be returned from the start parameter
  • Negative number - The length to be returned from the end of the string
  • If the length parameter is 0, NULL, or FALSE - it return an empty string
  • Technical Details

    Return Value: Returns the extracted part of a string, or FALSE on failure, or an empty string
    PHP Version: 4+
    Changelog: PHP 7.0 - If string = start (in characters long), it will return an empty string. Earlier versions returns FALSE.PHP 5.2.2 - 5.2.6 - If start has the position of a negative truncation, FALSE is returned. Other versions get the string from start.

    More Examples

    Example

    Using the start parameter with different positive and negative numbers: <?phpecho substr("Hello world",10)."<br>";echo substr("Hello world",1)."<br>";echo substr("Hello world",3)."<br>";echo substr("Hello world",7)."<br>";echo substr("Hello world",-1)."<br>";echo substr("Hello world",-10)."<br>";echo substr("Hello world",-8)."<br>"; echo substr("Hello world",-4)."<br>";?> Try it Yourself »

    Example

    Using the start and length parameters with different positive and negative numbers: <?phpecho substr("Hello world",0,10)."<br>";echo substr("Hello world",1,8)."<br>";echo substr("Hello world",0,5)."<br>";echo substr("Hello world",6,6)."<br>";echo substr("Hello world",0,-1)."<br>";echo substr("Hello world",-10,-2)."<br>";echo substr("Hello world",0,-6)."<br>";?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Compare two strings: <?php echo substr_compare("Hello world","Hello world",0); ?> Try it Yourself »

    Definition and Usage

    The substr_compare() function compares two strings from a specified start position. Tip: This function is binary-safe and optionally case-sensitive.

    Syntax

    substr_compare(string1,string2,startpos,length,case)

    Parameter Values

    ParameterDescription
    string1Required. Specifies the first string to compare
    string2Required. Specifies the second string to compare
    startposRequired. Specifies where to start comparing in string1. If negative, it starts counting from the end of the string
    lengthOptional. Specifies how much of string1 to compare
    caseOptional. A boolean value that specifies whether or not to perform a case-sensitive compare:
  • FALSE - Default. Case-sensitive
  • TRUE - Case-insensitive
  • Technical Details

    Return Value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 (from startpos) is less than string2
  • >0 - if string1 (from startpos) is greater than string2
  • If length is equal or greater than length of string1, this function returns FALSE.
    PHP Version: 5+
    Changelog: As of PHP 5.5.11 - The length parameter can be 0.As of PHP 5.1, it is now possible to use a negative startpos.

    More Examples

    Example

    Compare two strings, when start position in string1 for the comparison is 6th: <?php echo substr_compare("Hello world","world",6); ?> Try it Yourself »

    Example

    Using all parameters: <?phpecho substr_compare("world","or",1,2); echo substr_compare("world","ld",-2,2); echo substr_compare("world","orl",1,2); echo substr_compare("world","OR",1,2,TRUE); echo substr_compare("world","or",1,3); echo substr_compare("world","rl",1,2); ?> Try it Yourself »

    Example

    Different return values: <?phpecho substr_compare("Hello world!","Hello world!",0); // the two strings are equalecho substr_compare("Hello world!","Hello",0); // string1 is greater than string2echo substr_compare("Hello world!","Hello world! Hello!",0); // str1 is less than str2 ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Count the number of times "world" occurs in the string: <?php echo substr_count("Hello world. The world is nice","world"); ?> Try it Yourself » The substr_count() function counts the number of times a substring occurs in a string. Note: The substring is case-sensitive. Note: This function does not count overlapped substrings (see example 2). Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see example 3).

    Syntax

    substr_count(string,substring,start,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    substringRequired. Specifies the string to search for
    startOptional. Specifies where in string to start searching. If negative, it starts counting from the end of the string
    lengthOptional. Specifies the length of the search

    Technical Details

    Return Value: Returns the the number of times the substring occurs in the string
    PHP Version: 4+
    Changelog: PHP 7.1 - The length parameters can be 0 or a negative number. PHP 7.1 - The start parameters can be a negative number.PHP 5.1 - The start and length parameters were added.

    More Examples

    Example

    Using all parameters: <?php $str = "This is nice";echo strlen($str)."<br>"; // Using strlen() to return the string lengthecho substr_count($str,"is")."<br>"; // The number of times "is" occurs in the stringecho substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i" ?> Try it Yourself »

    Example

    Overlapped substrings: <?php $str = "abcabcab"; echo substr_count($str,"abcab"); // This function does not count overlapped substrings ?> Try it Yourself »

    Example

    If the start and length parameters exceeds the string length, this function will output a warning: <?php echo $str = "This is nice";substr_count($str,"is",3,9); ?> This will output a warning because the length value exceeds the string length (3+9 is greater than 12) PHP String Reference PHP String Reference

    Example

    Replace "Hello" with "world": <?php echo substr_replace("Hello","world",0); ?> Try it Yourself »

    Definition and Usage

    The substr_replace() function replaces a part of a string with another string. Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0. Note: This function is binary-safe.

    Syntax

    substr_replace(string,replacement,start,length)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    replacementRequired. Specifies the string to insert
    startRequired. Specifies where to start replacing in the string
  • A positive number - Start replacing at the specified position in the string
  • Negative number - Start replacing at the specified position from the end of the string
  • 0 - Start replacing at the first character in the string
  • lengthOptional. Specifies how many characters should be replaced. Default is the same length as the string.
  • A positive number - The length of string to be replaced
  • A negative number - How many characters should be left at end of string after replacing
  • 0 - Insert instead of replace
  • Technical Details

    Return Value: Returns the replaced string. If the string is an array then the array is returned
    PHP Version: 4+
    Changelog: As of PHP 4.3.3, all parameters now accept arrays

    More Examples

    Example

    Start replacing at the 6th position in the string (replace "world" with "earth"): <?php echo substr_replace("Hello world","earth",6); ?> Try it Yourself »

    Example

    Start replacing at the 5th position from the end of the string (replace "world" with "earth"): <?php echo substr_replace("Hello world","earth",-5); ?> Try it Yourself »

    Example

    Insert "Hello" at the beginning of "world": <?php echo substr_replace("world","Hello ",0,0); ?> Try it Yourself »

    Example

    Replace multiple strings at once. Replace "AAA" in each string with "BBB": <?php$replace = array("1: AAA","2: AAA","3: AAA");echo implode("<br>",substr_replace($replace,'BBB',3,3)); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"): <?php $str = "Hello World!"; echo $str . "<br>"; echo trim($str,"Hed!"); ?> Try it Yourself »

    Definition and Usage

    The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions:
  • ltrim() - Removes whitespace or other predefined characters from the left side of a string
  • rtrim() - Removes whitespace or other predefined characters from the right side of a string
  • Syntax

    trim(string,charlist)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to check
    charlistOptional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
  • "\0" - NULL
  • "\t" - tab
  • "\n" - new line
  • "\x0B" - vertical tab
  • "\r" - carriage return
  • " " - ordinary white space
  • Technical Details

    Return Value: Returns the modified string
    PHP Version: 4+
    Changelog: The charlist parameter was added in PHP 4.1

    More Examples

    Example

    Remove whitespaces from both sides of a string: <?php $str = " Hello World! "; echo "Without trim: " . $str; echo "<br>"; echo "With trim: " . trim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without trim: Hello World! <br>With trim: Hello World! </body> </html> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! Try it Yourself »

    Example

    Remove newlines (\n) from both sides of the string: <?php $str = "\n\n\nHello World!\n\n\n"; echo "Without trim: " . $str; echo "<br>"; echo "With trim: " . trim($str); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> Without trim: Hello World! <br>With trim: Hello World! </body> </html> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! Try it Yourself » PHP String Reference PHP String Reference

    Example

    Convert the first character of "hello" to uppercase: <?phpecho ucfirst("hello world!");?> Try it Yourself »

    Definition and Usage

    The ucfirst() function converts the first character of a string to uppercase. Related functions:
  • lcfirst() - converts the first character of a string to lowercase
  • ucwords() - converts the first character of each word in a string to uppercase
  • strtoupper() - converts a string to uppercase
  • strtolower() - converts a string to lowercase
  • Syntax

    ucfirst(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 4+
    PHP String Reference PHP String Reference

    Example

    Convert the first character of each word to uppercase: <?php echo ucwords("hello world"); ?> Try it Yourself »

    Definition and Usage

    The ucwords() function converts the first character of each word in a string to uppercase. Note: This function is binary-safe. Related functions:
  • ucfirst() - converts the first character of a string to uppercase
  • lcfirst() - converts the first character of a string to lowercase
  • strtoupper() - converts a string to uppercase
  • strtolower() - converts a string to lowercase
  • Syntax

    ucwords(string, delimiters)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to convert
    delimitersOptional. Specifies the word separator character

    Technical Details

    Return Value: Returns the converted string
    PHP Version: 4+
    Changelog: PHP 5.4 - Added the delimiters parameter

    More Examples

    Example

    Convert the first character of each word to uppercase, with a custom word separator added: <?php echo ucwords("hello|world", "|"); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Write some text to a text file named "test.txt": <?php$number = 9;$str = "Beijing";$file = fopen("test.txt","w"); echo vfprintf($file,"There are %u million bicycles in %s.",array($number,$str)); ?> The output of the code above will be: 40 The following text will be written to the file "test.txt": There are 9 million bicycles in Beijing.

    Definition and Usage

    The vfprintf() function writes a formatted string to a specified output stream (example: file or database). Unlike fprintf(), the arguments in vfprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: fprintf(), printf(), sprintf(), vprintf() and vsprintf().

    Syntax

    vfprintf(stream,format,argarray)

    Parameter Values

    ParameterDescription
    streamRequired. Specifies where to write/output the string
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    argarrayRequired. An array with arguments to be inserted at the % signs in the format string

    Technical Details

    Return Value: Returns the length of the written string
    PHP Version: 5+

    More Examples

    Example

    Write some text to a file: <?php $num1 = 123; $num2 = 456; $file = fopen("test.txt","w"); vfprintf($file,"%f%f",array($num1,$num2)); ?> The following text will be written to the file "test.txt": 123.000000456.000000

    Example

    Use of placeholders: <?php $number = 123; $file = fopen("test.txt","w"); vfprintf($file,"With 2 decimals: %1\$.2f \nWith no decimals: %1\$u",array($number)); ?> The following text will be written to the file "test.txt": With 2 decimals: 123.00 With no decimals: 123

    Example

    Using printf() to demonstrate all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signprintf("%%b = %b <br>",$num1); // Binary numberprintf("%%c = %c <br>",$char); // The ASCII Characterprintf("%%d = %d <br>",$num1); // Signed decimal numberprintf("%%d = %d <br>",$num2); // Signed decimal numberprintf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)printf("%%g = %g <br>",$num1); // Shorter of %e and %fprintf("%%G = %G <br>",$num1); // Shorter of %E and %fprintf("%%o = %o <br>",$num1); // Octal numberprintf("%%s = %s <br>",$num1); // Stringprintf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)printf("%%+d = %+d <br>",$num1); // Sign specifier (positive) printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Output a formatted string: <?php$number = 9;$str = "Beijing";vprintf("There are %u million bicycles in %s.",array($number,$str));?> Try it Yourself »

    Definition and Usage

    The vprintf() function outputs a formatted string. Unlike printf(), the arguments in vprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: sprintf(), printf(), vsprintf(), fprintf() and vfprintf()

    Syntax

    vprintf(format,argarray)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    argarrayRequired. An array with arguments to be inserted at the % signs in the format string

    Technical Details

    Return Value: Returns the length of the outputted string
    PHP Version: 4.1.0+

    More Examples

    Example

    Using the format value %f: <?php $num1 = 123; $num2 = 456; vprintf("%f%f",array($num1,$num2)); ?> Try it Yourself »

    Example

    Use of placeholders: <?php $number = 123; vprintf("With 2 decimals: %1\$.2f <br>With no decimals: %1\$u",array($number)); ?> Try it Yourself »

    Example

    Using printf() to demonstrate all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signprintf("%%b = %b <br>",$num1); // Binary numberprintf("%%c = %c <br>",$char); // The ASCII Characterprintf("%%d = %d <br>",$num1); // Signed decimal numberprintf("%%d = %d <br>",$num2); // Signed decimal numberprintf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)printf("%%g = %g <br>",$num1); // Shorter of %e and %fprintf("%%G = %G <br>",$num1); // Shorter of %E and %fprintf("%%o = %o <br>",$num1); // Octal numberprintf("%%s = %s <br>",$num1); // Stringprintf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)printf("%%+d = %+d <br>",$num1); // Sign specifier (positive) printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)?> Try it Yourself »

    Example

    A demonstration of string specifiers: <?php$str1 = "Hello";$str2 = "Hello world!";vprintf("[%s]<br>",array($str1)); vprintf("[%8s]<br>",array($str1));vprintf("[%-8s]<br>",array($str1)); vprintf("[%08s]<br>",array($str1)); vprintf("[%'*8s]<br>",array($str1)); vprintf("[%8.8s]<br>",array($str2)); ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Write a formatted string to a variable: <?php$number = 9;$str = "Beijing";$txt = vsprintf("There are %u million bicycles in %s.",array($number,$str));echo $txt;?> Try it Yourself »

    Definition and Usage

    The vsprintf() function writes a formatted string to a variable. Unlike sprintf(), the arguments in vsprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example two. Tip: Related functions: fprintf(), vfprintf(), printf(), sprintf() and vprintf().

    Syntax

    vsprintf(format,argarray)

    Parameter Values

    ParameterDescription
    formatRequired. Specifies the string and how to format the variables in it.Possible format values:
  • %% - Returns a percent sign
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E - Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %g - shorter of %e and %f
  • %G - shorter of %E and %f
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)
  • Additional format values. These are placed between the % and the letter (example %.2f):
  • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - (Left-justifies the variable value)
  • [0-9] (Specifies the minimum width held of to the variable value)
  • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • Note: If multiple additional format values are used, they must be in the same order as above.
    argarrayRequired. An array with arguments to be inserted at the % signs in the format string

    Technical Details

    Return Value: Returns array values as a formatted string
    PHP Version: 4.1.0+

    More Examples

    Example

    Using the format value %f: <?php $num1 = 123; $num2 = 456; $txt = vsprintf("%f%f",array($num1,$num2)); echo $txt; ?> Try it Yourself »

    Example

    Use of placeholders: <?php $number = 123; $txt = vsprintf("With 2 decimals: %1\$.2f <br>With no decimals: %1\$u",array($number)); echo $txt; ?> Try it Yourself »

    Example

    Using sprintf() to demonstrate all possible format values: <?php$num1 = 123456789;$num2 = -123456789;$char = 50; // The ASCII Character 50 is 2// Note: The format value "%%" returns a percent signecho sprintf("%%b = %b",$num1)."<br>"; // Binary numberecho sprintf("%%c = %c",$char)."<br>"; // The ASCII Character echo sprintf("%%d = %d",$num1)."<br>"; // Signed decimal numberecho sprintf("%%d = %d",$num2)."<br>"; // Signed decimal numberecho sprintf("%%e = %e",$num1)."<br>"; // Scientific notation (lowercase)echo sprintf("%%E = %E",$num1)."<br>"; // Scientific notation (uppercase)echo sprintf("%%u = %u",$num1)."<br>"; // Unsigned decimal number (positive) echo sprintf("%%u = %u",$num2)."<br>"; // Unsigned decimal number (negative) echo sprintf("%%f = %f",$num1)."<br>"; // Floating-point number (local settings aware)echo sprintf("%%F = %F",$num1)."<br>"; // Floating-point number (not local sett aware)echo sprintf("%%g = %g",$num1)."<br>"; // Shorter of %e and %fecho sprintf("%%G = %G",$num1)."<br>"; // Shorter of %E and %fecho sprintf("%%o = %o",$num1)."<br>"; // Octal number echo sprintf("%%s = %s",$num1)."<br>"; // Stringecho sprintf("%%x = %x",$num1)."<br>"; // Hexadecimal number (lowercase)echo sprintf("%%X = %X",$num1)."<br>"; // Hexadecimal number (uppercase)echo sprintf("%%+d = %+d",$num1)."<br>"; // Sign specifier (positive)echo sprintf("%%+d = %+d",$num2)."<br>"; // Sign specifier (negative)?> Try it Yourself »

    Example

    A demonstration of string specifiers: <?php$str1 = "Hello";$str2 = "Hello world!";echo vsprintf("[%s]",array($str1))."<br>"; echo vsprintf("[%8s]",array($str1))."<br>";echo vsprintf("[%-8s]",array($str1))."<br>"; echo vsprintf("[%08s]",array($str1))."<br>"; echo vsprintf("[%'*8s]",array($str1))."<br>"; echo vsprintf("[%8.8s]",array($str2))."<br>"; ?> Try it Yourself » PHP String Reference PHP String Reference

    Example

    Wrap a string into new lines when it reaches a specific length: <?php $str = "An example of a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br>\n"); ?> Try it Yourself »

    Definition and Usage

    The wordwrap() function wraps a string into new lines when it reaches a specific length. Note: This function may leave white spaces at the beginning of a line.

    Syntax

    wordwrap(string,width,break,cut)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the string to break up into lines
    widthOptional. Specifies the maximum line width. Default is 75
    breakOptional. Specifies the characters to use as break. Default is "\n"
    cut Optional. Specifies whether words longer than the specified width should be wrapped:
  • FALSE - Default. No-wrap
  • TRUE - Wrap
  • Technical Details

    Return Value: Returns the string broken into lines on success, or FALSE on failure.
    PHP Version: 4.0.2+
    Changelog: The cut parameter was added in PHP 4.0.3

    More Examples

    Example

    Using all parameters: <?php $str = "An example of a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br>\n",TRUE); ?> Try it Yourself »

    Example

    Wrap a string into new lines: <?php $str = "An example of a long word is: Supercalifragulistic"; echo wordwrap($str,15); ?> The HTML output of the code above will be (View Source): <!DOCTYPE html><html> <body> An example of a long word is: Supercalifragulistic </body> </html> The browser output of the code above will be: An example of a long word is: Supercalifragulistic Try it Yourself » PHP String Reference

    Variable Handling Functions

    The PHP variable handling functions are part of the PHP core. No installation is required to use these functions.
    FunctionDescription
    boolval()Returns the boolean value of a variable
    debug_zval_dump()Dumps a string representation of an internal zend value to output
    doubleval()Alias of floatval()
    empty()Checks whether a variable is empty
    floatval()Returns the float value of a variable
    get_defined_vars()Returns all defined variables, as an array
    get_resource_type()Returns the type of a resource
    gettype()Returns the type of a variable
    intval()Returns the integer value of a variable
    is_array()Checks whether a variable is an array
    is_bool()Checks whether a variable is a boolean
    is_callable()Checks whether the contents of a variable can be called as a function
    is_countable()Checks whether the contents of a variable is a countable value
    is_double()Alias of is_float()
    is_float()Checks whether a variable is of type float
    is_int() Checks whether a variable is of type integer
    is_integer()Alias of is_int()
    is_iterable()Checks whether the contents of a variable is an iterable value
    is_long()Alias of is_int()
    is_null()Checks whether a variable is NULL
    is_numeric()Checks whether a variable is a number or a numeric string
    is_object()Checks whether a variable is an object
    is_real()Alias of is_float()
    is_resource()Checks whether a variable is a resource
    is_scalar()Checks whether a variable is a scalar
    is_string()Checks whether a variable is of type string
    isset()Checks whether a variable is set (declared and not NULL)
    print_r()Prints the information about a variable in a human-readable way
    serialize()Converts a storable representation of a value
    settype()Converts a variable to a specific type
    strval()Returns the string value of a variable
    unserialize()Converts serialized data back into actual data
    unset()Unsets a variable
    var_dump()Dumps information about one or more variables
    var_export()Returns structured information (valid PHP code) about a variable
    PHP Variable Handling Reference

    Example

    Return the boolean value of different variables: <?php echo "0: " .(boolval(0) ? 'true' : 'false') . "<br>";echo "4: " .(boolval(42) ? 'true' : 'false') . "<br>";echo '": ' .(boolval(") ? 'true' : 'false') . "<br>";echo '"Hello": ' .(boolval("Hello") ? 'true' : 'false') . "<br>"; echo '"0": ' .(boolval("0") ? 'true' : 'false') . "<br>";echo "[3, 5]: " .(boolval([3, 5]) ? 'true' : 'false') . "<br>";echo "[]: " .(boolval([]) ? 'true' : 'false') . "<br>";?> Try it Yourself »

    Definition and Usage

    The boolval() function returns the boolean value of a variable.

    Syntax

    boolval(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check. Must be a scalar type

    Technical Details

    Return Value: The boolean value of the variable
    Return Type: Boolean
    PHP Version: 5.5+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Dump a string representation of an internal zend value to output: <?php $a = "Hello world!";echo debug_zval_dump($a) . "<br>";?> Try it Yourself »

    Definition and Usage

    The debug_zval_dump() function dumps a string representation of an internal zend value to output.

    Syntax

    debug_zval_dump(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to be evaluated

    Technical Details

    Return Value: Nothing
    Return Type: -
    PHP Version: 4.2+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the float value of different variables: <?php $a = "1234.56789";echo doubleval($a) . "<br>";$b = "1234.56789Hello";echo doubleval($b) . "<br>";$c = "Hello1234.56789";echo doubleval($c) . "<br>";?> Try it Yourself »

    Definition and Usage

    The doubleval() function returns the float value of a variable. This function is an alias of floatval().

    Syntax

    doubleval(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check. Must be a scalar type

    Technical Details

    Return Value: The float value of the variable on success, 0 on failure. An empty array will return 0, and a non-empty array will return 1
    Return Type: Float
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether the contents of a variable is a countable value or not: <?php $a = "Hello";echo "a is " . is_countable($a) . "<br>"; $b = array("red", "green", "blue");echo "b is " . is_countable($b) . "<br>";$c = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");echo "c is " . is_countable($c) . "<br>";$d = [1, 2, 3];echo "d is " . is_countable($d) . "<br>";?> Try it Yourself »

    Definition and Usage

    The is_countable() function checks whether the contents of a variable is a countable value or not. This function returns true (1) if the variable is countable, otherwise it returns false/nothing.

    Syntax

    is_countable(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is countable, FALSE otherwise
    Return Type: Boolean
    PHP Version: 7.3+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is empty. Also check whether the variable is set/declared: <?php $a = 0;// True because $a is emptyif (empty($a)) { echo "Variable 'a' is empty.<br>";}// True because $a is setif (isset($a)) { echo "Variable 'a' is set";}?> Try it Yourself »

    Definition and Usage

    The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty:
  • 0
  • 0.0
  • "0"
  • "
  • NULL
  • FALSE
  • array()
  • Syntax

    empty(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: FALSE if variable exists and is not empty, TRUE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Changelog: PHP 5.5: Support for expressions, not only variablesPHP 5.4: Non-numeric offsets of strings returns TRUE
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the float value of different variables: <?php $a = "1234.56789";echo floatval($a) . "<br>";$b = "1234.56789Hello";echo floatval($b) . "<br>";$c = "Hello1234.56789";echo floatval($c) . "<br>";?> Try it Yourself »

    Definition and Usage

    The floatval() function returns the float value of a variable.

    Syntax

    floatval(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check. Must be a scalar type

    Technical Details

    Return Value: The float value of the variable on success, 0 on failure. An empty array will return 0, and a non-empty array will return 1
    Return Type: Float
    PHP Version: 4.2+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return all defined variables, as an array: <?php $a = array("red", "green", "blue");$arr = get_defined_vars(); print_r($arr["a"]);?> Try it Yourself »

    Definition and Usage

    The get_defined_vars() function returns all defined variables, as an array.

    Syntax

    get_defined_vars();

    Parameter Values

    None.

    Technical Details

    Return Value: All the defined variables as a multidimensional array
    Return Type: Array
    PHP Version: 4.0.4+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the resource type: <?php $file = fopen("test.txt","r");echo get_resource_type($file);?> Run Example »

    Definition and Usage

    The get_resource_type() function returns the type of a resource.

    Syntax

    get_resource_type(resource);

    Parameter Values

    ParameterDescription
    resourceRequired. Specifies the resource to check

    Technical Details

    Return Value: The type as a string on success, if type is not identified it returns "unknown", if resource is not a resource it returns NULL and generates an error
    Return Type: String
    PHP Version: 4.0.2+
    PHP Changelog: PHP 5.3: If resource is not a resource it returns NULL. Earlier, the returned value was FALSE
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the type of different variables: <?php $a = 3;echo gettype($a) . "<br>";$b = 3.2;echo gettype($b) . "<br>"; $c = "Hello";echo gettype($c) . "<br>";$d = array();echo gettype($d) . "<br>";$e = array("red", "green", "blue");echo gettype($e) . "<br>";$f = NULL;echo gettype($f) . "<br>"; $g = false;echo gettype($g) . "<br>";?> Try it Yourself »

    Definition and Usage

    The gettype() function returns the type of a variable.

    Syntax

    gettype(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: The type as a string. Can be one of the following values: "boolean", "integer", "double", "string", "array", "object", "resource", "NULL", "unknown type"
    Return Type: String
    PHP Version: 4.0+
    PHP Changelog: PHP 7.2: Closed resources are now returned as "resource (closed)". Earlier, the returned value was "unknown type".
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the integer value of different variables: <?php $a = 32;echo intval($a) . "<br>";$b = 3.2;echo intval($b) . "<br>"; $c = "32.5";echo intval($c) . "<br>";$d = array();echo intval($d) . "<br>";$e = array("red", "green", "blue");echo intval($e) . "<br>";?> Try it Yourself »

    Definition and Usage

    The intval() function returns the integer value of a variable.

    Syntax

    intval(variable, base);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check
    baseOptional. Specifies the base to use for the conversion. Only has effect if variable is a string. Default base is 10

    Technical Details

    Return Value: The integer value of the variable on success, 0 on failure. An empty array will return 0, and a non-empty array will return 1
    Return Type: Integer
    PHP Version: 4.0+
    PHP Changelog: PHP 5.1: When an object is passed to variable, it throws E_NOTICE and returns 1
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is an array or not: <?php $a = "Hello";echo "a is " . is_array($a) . "<br>"; $b = array("red", "green", "blue");echo "b is " . is_array($b) . "<br>";$c = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");echo "c is " . is_array($c) . "<br>";$d = "red, green, blue";echo "d is " . is_array($d) . "<br>";?> Try it Yourself »

    Definition and Usage

    The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

    Syntax

    is_array(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is an array, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is a boolean or not: <?php $a = 1;echo "a is " . is_bool($a) . "<br>"; $b = 0;echo "b is " . is_bool($b) . "<br>";$c = true;echo "c is " . is_bool($c) . "<br>";$d = false;echo "d is " . is_bool($d) . "<br>";?> Try it Yourself »

    Definition and Usage

    The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

    Syntax

    is_bool(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a boolean, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether the contents of a variable can be called as a function or not: <?php function test1(){}echo "test1 is callable: " . is_callable("test1"); echo "<br>";echo "test2 is callable: " . is_callable("test2");?> Try it Yourself »

    Definition and Usage

    The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.

    Syntax

    is_callable(variable, syntax_only, name );

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check
    syntax_onlyOptional. If set to TRUE, the function only verifies if variable is a function or method. It will reject variables that are not strings, or arrays without a valid structure to be used as a callback. Default is false
    nameOptional. Returns a "callable name" (only for classes)

    Technical Details

    Return Value: TRUE if variable is callable, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0.6+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type float or not: <?php $a = 32;echo "a is " . is_double($a) . "<br>";$b = 0;echo "b is " . is_double($b) . "<br>";$c = 32.5;echo "c is " . is_double($c) . "<br>";$d = "32";echo "d is " . is_double($d) . "<br>";$e = true;echo "e is " . is_double($e) . "<br>";$f = "null";echo "f is " . is_double($f) . "<br>";$g = 1.e3;echo "g is " . is_double($g) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_double() function checks whether a variable is of type float or not. This function is an alias of is_float().

    Syntax

    is_double(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a float, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type float or not: <?php $a = 32;echo "a is " . is_float($a) . "<br>";$b = 0;echo "b is " . is_float($b) . "<br>";$c = 32.5;echo "c is " . is_float($c) . "<br>";$d = "32";echo "d is " . is_float($d) . "<br>";$e = true;echo "e is " . is_float($e) . "<br>";$f = "null";echo "f is " . is_float($f) . "<br>";$g = 1.e3;echo "g is " . is_float($g) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.

    Syntax

    is_float(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a float, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type integer or not: <?php $a = 32;echo "a is " . is_int($a) . "<br>";$b = 0;echo "b is " . is_int($b) . "<br>";$c = 32.5;echo "c is " . is_int($c) . "<br>"; $d = "32";echo "d is " . is_int($d) . "<br>";$e = true; echo "e is " . is_int($e) . "<br>";$f = "null";echo "f is " . is_int($f) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

    Syntax

    is_int(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is an integer, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type integer or not: <?php $a = 32;echo "a is " . is_integer($a) . "<br>";$b = 0;echo "b is " . is_integer($b) . "<br>";$c = 32.5;echo "c is " . is_integer($c) . "<br>"; $d = "32";echo "d is " . is_integer($d) . "<br>";$e = true; echo "e is " . is_integer($e) . "<br>";$f = "null";echo "f is " . is_integer($f) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_integer() function checks whether a variable is of type integer or not. This function is an alias of is_int().

    Syntax

    is_integer(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is an integer, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether the contents of a variable is an iterable value or not: <?php $a = "Hello";echo "a is " . is_iterable($a) . "<br>"; $b = array("red", "green", "blue");echo "b is " . is_iterable($b) . "<br>";$c = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");echo "c is " . is_iterable($c) . "<br>";$d = [1, 2, 3];echo "d is " . is_iterable($d) . "<br>";?> Try it Yourself »

    Definition and Usage

    The is_iterable() function checks whether the contents of a variable is an iterable value or not. This function returns true (1) if the variable is iterable, otherwise it returns false/nothing.

    Syntax

    is_iterable(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is iterable, FALSE otherwise
    Return Type: Boolean
    PHP Version: 7.1+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type integer or not: <?php $a = 32;echo "a is " . is_long($a) . "<br>";$b = 0;echo "b is " . is_long($b) . "<br>";$c = 32.5;echo "c is " . is_long($c) . "<br>"; $d = "32";echo "d is " . is_long($d) . "<br>";$e = true; echo "e is " . is_long($e) . "<br>";$f = "null";echo "f is " . is_long($f) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_long() function checks whether a variable is of type integer or not. This function is an alias of is_int().

    Syntax

    is_long(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is an integer, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is NULL or not: <?php $a = 0;echo "a is " . is_null($a) . "<br>";$b = null;echo "b is " . is_null($b) . "<br>";$c = "null";echo "c is " . is_null($c) . "<br>";$d = NULL;echo "d is " . is_null($d) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

    Syntax

    is_null(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is NULL, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0.4+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is a number or a numeric string, or not: <?php $a = 32;echo "a is " . is_numeric($a) . "<br>";$b = 0;echo "b is " . is_numeric($b) . "<br>";$c = 32.5;echo "c is " . is_numeric($c) . "<br>";$d = "32";echo "d is " . is_numeric($d) . "<br>"; $e = true;echo "e is " . is_numeric($e) . "<br>";$f = null; echo "f is " . is_numeric($f) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

    Syntax

    is_numeric(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a number or a numeric string, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is an object or not: <?php function get_cars($obj) { if (!is_object($obj)) { return false; }return $obj->cars;}$obj = new stdClass();$obj->cars = array("Volvo", "BMW", "Audi");var_dump(get_cars(null)); echo "<br>";var_dump(get_cars($obj));?> Try it Yourself »

    Definition and Usage

    The is_object() function checks whether a variable is an object. This function returns true (1) if the variable is an object, otherwise it returns false/nothing.

    Syntax

    is_object(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is an object, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Changelog: PHP 7.2: This function now returns true for unserialized objects without a class definition. Earlier false was returned
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type float or not: <?php $a = 32;echo "a is " . is_real($a) . "<br>";$b = 0;echo "b is " . is_real($b) . "<br>";$c = 32.5;echo "c is " . is_real($c) . "<br>";$d = "32";echo "d is " . is_real($d) . "<br>";$e = true;echo "e is " . is_real($e) . "<br>";$f = "null";echo "f is " . is_real($f) . "<br>";$g = 1.e3;echo "g is " . is_real($g) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_real() function checks whether a variable is of type float or not. This function is an alias of is_float().

    Syntax

    is_real(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a float, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is a resource or not: <?php $file = fopen("test.txt","r");if (is_resource($file)) { echo "File is open";} else { echo "Error open file";}?> Run Example »

    Definition and Usage

    The is_resource() function checks whether a variable is a resource or not. Note: The is_resource() function will return FALSE if the resource has been closed. This function returns true (1) if the variable is a resource, otherwise it returns false/nothing.

    Syntax

    is_resource(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a resource, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is a scalar or not: <?php $a = "Hello";echo "a is " . is_scalar($a) . "<br>";$b = 0;echo "b is " . is_scalar($b) . "<br>";$c = 32;echo "c is " . is_scalar($c) . "<br>";$d = NULL;echo "d is " . is_scalar($d) . "<br>"; $e = array("red", "green", "blue");echo "e is " . is_scalar($e) . "<br>";?> Try it Yourself »

    Definition and Usage

    The is_scalar() function checks whether a variable is a scalar or not. This function returns true (1) if the variable is a scalar, otherwise it returns false/nothing. Integers, floats, strings, or boolean can be scalar variables. Arrays, objects, and resources are not.

    Syntax

    is_scalar(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a scalar, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0.5+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is of type string or not: <?php $a = "Hello";echo "a is " . is_string($a) . "<br>";$b = 0;echo "b is " . is_string($b) . "<br>";$c = 32;echo "c is " . is_string($c) . "<br>";$d = "32";echo "d is " . is_string($d) . "<br>";$e = true;echo "e is " . is_string($e) . "<br>";$f = "null";echo "f is " . is_string($f) . "<br>";$g = ";echo "g is " . is_string($g) . "<br>"; ?> Try it Yourself »

    Definition and Usage

    The is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.

    Syntax

    is_string(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: TRUE if variable is a string, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Check whether a variable is empty. Also check whether the variable is set/declared: <?php $a = 0;// True because $a is setif (isset($a)) { echo "Variable 'a' is set.<br>";}$b = null;// False because $b is NULLif (isset($b)) { echo "Variable 'b' is set.";}?> Try it Yourself »

    Definition and Usage

    The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false. Note: If multiple variables are supplied, then this function will return true only if all of the variables are set. Tip: A variable can be unset with the unset() function.

    Syntax

    isset(variable, ....);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check
    ...Optional. Another variable to check

    Technical Details

    Return Value: TRUE if variable exists and is not NULL, FALSE otherwise
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Changelog: PHP 5.4: Non-numeric offsets of strings now returns FALSE
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Print the information about some variables in a more human-readable way: <?php $a = array("red", "green", "blue");print_r($a);echo "<br>"; $b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");print_r($b);?> Try it Yourself »

    Definition and Usage

    The print_r() function prints the information about a variable in a more human-readable way.

    Syntax

    print_r(variable, return);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to return information about
    returnOptional. When set to true, this function will return the information (not print it). Default is false

    Technical Details

    Return Value: If variable is integer, float, or string, the value itself will be printed. If variable is array or object, this function returns keys and elements. If the return parameter is set to TRUE, this function returns a string
    Return Type: True or String
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Convert a storable representation of a value: <?php $data = serialize(array("Red", "Green", "Blue"));echo $data;?> Try it Yourself »

    Definition and Usage

    The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

    Syntax

    serialize(value);

    Parameter Values

    ParameterDescription
    valueRequired. Specifies the value to be serialized

    Technical Details

    Return Value: A string that contains a byte-stream representation of value. The string can be stored anywhere
    Return Type: String
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Convert variables to specific types: <?php $a = "32"; // string settype($a, "integer"); // $a is now integer$b = 32; // integer settype($b, "string"); // $b is now string$c = true; // boolean settype($c, "integer"); // $c is now integer (1)?> Try it Yourself »

    Definition and Usage

    The settype() function converts a variable to a specific type.

    Syntax

    settype(variable, type);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to convert
    typeRequired. Specifies the type to convert variable to. The possible types are: boolean, bool, integer, int, float, double, string, array, object, null

    Technical Details

    Return Value: TRUE on success, FALSE on failure
    Return Type: Boolean
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Return the string value of different variables: <?php $a = "Hello";echo strval($a) . "<br>";$b = "1234.56789";echo strval($b) . "<br>";$c = "1234.56789Hello";echo strval($c) . "<br>";$d = "Hello1234.56789";echo strval($d) . "<br>"; $e = 1234;echo strval($e) . "<br>";?> Try it Yourself »

    Definition and Usage

    The strval() function returns the string value of a variable.

    Syntax

    strval(variable);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check

    Technical Details

    Return Value: The string value of the variable on success
    Return Type: String
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Convert serialized data back into actual data: <?php $data = serialize(array("Red", "Green", "Blue"));echo $data . "<br>";$test = unserialize($data);var_dump($test);?> Try it Yourself »

    Definition and Usage

    The unserialize() function converts serialized data back into actual data.

    Syntax

    unserialize(string, options);

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the serialized string
    optionsOptional. Specifies options to be provided to the function, as an associative array. Can be either an array of class names which should be accepted, false to accept no classes, or true to accept all classes. True is default.

    Technical Details

    Return Value: The converted value. Can be a boolean, integer, float, string, array or object. FALSE, and an E_NOTICE on failure
    Return Type: Boolean, integer, float, string, array or object
    PHP Version: 4.0+
    PHP Changelog: PHP 7.0: Added the options parameter
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Unset variables: <?php $a = "Hello world!";echo "The value of variable 'a' before unset: " . $a . "<br>"; unset($a);echo "The value of variable 'a' after unset: " . $a;?> Try it Yourself »

    Definition and Usage

    The unset() function unsets a variable.

    Syntax

    unset(variable, ....);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to unset
    ...Optional. Another variable to unset

    Technical Details

    Return Value: None
    Return Type: None
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Dump information about different variables: <?php $a = 32;echo var_dump($a) . "<br>";$b = "Hello world!";echo var_dump($b) . "<br>";$c = 32.5;echo var_dump($c) . "<br>";$d = array("red", "green", "blue");echo var_dump($d) . "<br>"; $e = array(32, "Hello world!", 32.5, array("red", "green", "blue"));echo var_dump($e) . "<br>";// Dump two variablesecho var_dump($a, $b) . "<br>";?> Try it Yourself »

    Definition and Usage

    The var_dump() function dumps information about one or more variables. The information holds type and value of the variable(s).

    Syntax

    var_dump(var1, var2, ...);

    Parameter Values

    ParameterDescription
    var1, var2, ...Required. Specifies the variable(s) to dump information from

    Technical Details

    Return Value: Nothing
    Return Type: -
    PHP Version: 4.0+
    PHP Variable Handling Reference PHP Variable Handling Reference

    Example

    Output structured information about variables: <?php $a = 32;echo var_export($a) . "<br>";$b = "Hello world!";echo var_export($b) . "<br>";$c = 32.5;echo var_export($c) . "<br>";$d = array("red", "green", "blue");echo var_export($d) . "<br>"; $e = array(32, "Hello world!", 32.5, array("red", "green", "blue")); echo var_export($e) . "<br>";?> Try it Yourself »

    Definition and Usage

    The var_export() function outputs or returns structured information about a variable. This function works similar to var_dump(), except that the returned value for this function is valid PHP code.

    Syntax

    var_export(variable, return);

    Parameter Values

    ParameterDescription
    variableRequired. Specifies the variable to check
    returnOptional. If set to true, it returns the variable representation instead of outputting it

    Technical Details

    Return Value: If return is set to TRUE, it returns the variable representation. Otherwise, it returns NULL
    Return Type: Mixed
    PHP Version: 4.2+
    PHP Variable Handling Reference

    XML Parser Introduction

    The XML functions lets you parse, but not validate, XML documents. XML is a data format for standardized structured document exchange. More information on XML can be found in our XML Tutorial. This extension uses the Expat XML parser. Expat is an event-based parser, it views an XML document as a series of events. When an event occurs, it calls a specified function to handle it. Expat is a non-validating parser, and ignores any DTDs linked to a document. However, if the document is not well formed it will end with an error message. Because it is an event-based, non validating parser, Expat is fast and well suited for web applications. The XML parser functions lets you create XML parsers and define handlers for XML events.

    Installation

    The XML functions are part of the PHP core. There is no installation needed to use these functions.

    XML Parser Functions

    FunctionDescription
    utf8_decode()Decodes an UTF-8 string to ISO-8859-1
    utf8_encode()Encodes an ISO-8859-1 string to UTF-8
    xml_error_string()Returns an error string from the XML parser
    xml_get_current_byte_index()Returns the current byte index from the XML parser
    xml_get_current_column_number()Returns the current column number from the XML parser
    xml_get_current_line_number()Returns the current line number from the XML parser
    xml_get_error_code()Returns an error code from the XML parser
    xml_parse()Parses an XML document
    xml_parse_into_struct()Parses XML data into an array
    xml_parser_create_ns()Creates an XML parser with namespace support
    xml_parser_create()Creates an XML parser
    xml_parser_free()Frees an XML parser
    xml_parser_get_option()Returns options from an XML parser
    xml_parser_set_option()Sets options in an XML parser
    xml_set_character_data_handler()Sets up the character data handler for the XML parser
    xml_set_default_handler()Sets up the default data handler for the XML parser
    xml_set_element_handler()Sets up start and end element handlers for the XML parser
    xml_set_end_namespace_decl_handler()Sets up the end namespace declaration handler
    xml_set_external_entity_ref_handler()Sets up the external entity reference handler for the XML parser
    xml_set_notation_decl_handler()Sets up notation declaration handler for the XML parser
    xml_set_object()Allows to use XML parser within an object
    xml_set_processing_instruction_handler()Sets up processing instruction handler
    xml_set_start_namespace_decl_handler()Sets up the start namespace declaration handler
    xml_set_unparsed_entity_decl_handler()Sets handler function for unparsed entity declarations

    XML Parser Constants

    Constant
    XML_ERROR_NONE (integer)
    XML_ERROR_NO_MEMORY (integer)
    XML_ERROR_SYNTAX (integer)
    XML_ERROR_NO_ELEMENTS (integer)
    XML_ERROR_INVALID_TOKEN (integer)
    XML_ERROR_UNCLOSED_TOKEN (integer)
    XML_ERROR_PARTIAL_CHAR (integer)
    XML_ERROR_TAG_MISMATCH (integer)
    XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
    XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
    XML_ERROR_PARAM_ENTITY_REF (integer)
    XML_ERROR_UNDEFINED_ENTITY (integer)
    XML_ERROR_RECURSIVE_ENTITY_REF (integer)
    XML_ERROR_ASYNC_ENTITY (integer)
    XML_ERROR_BAD_CHAR_REF (integer)
    XML_ERROR_BINARY_ENTITY_REF (integer)
    XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
    XML_ERROR_MISPLACED_XML_PI (integer)
    XML_ERROR_UNKNOWN_ENCODING (integer)
    XML_ERROR_INCORRECT_ENCODING (integer)
    XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
    XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
    XML_OPTION_CASE_FOLDING (integer)
    XML_OPTION_TARGET_ENCODING (integer)
    XML_OPTION_SKIP_TAGSTART (integer)
    XML_OPTION_SKIP_WHITE (integer)
    XML_SAX_IMPL (string)
    PHP XML Parser Reference

    Example

    Decode a UTF-8 string to ISO-8859-1: <?php $text = "\xE0";echo utf8_encode($text) ."<br>";echo utf8_decode($text);?> Try it Yourself »

    Definition and Usage

    The utf8_decode() function decodes a UTF-8 string to ISO-8859-1. This function decodes a string, previously encoded with the utf8_encode() function, back to ISO-8859-1.

    Syntax

    utf8_decode(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies a UTF-8 encoded string to decode

    Technical Details

    Return Value: The decoded string on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Encode an ISO-8859-1 string to UTF-8: <?php $text = "\xE0";echo utf8_encode($text);?> Try it Yourself »

    Definition and Usage

    The utf8_encode() function encodes an ISO-8859-1 string to UTF-8. Unicode is a universal standard, and has been developed to describe all possible characters of all languages plus a lot of symbols with one unique number for each character/symbol. However, it is not always possible to transfer a Unicode character to another computer reliably. UTF-8 has been developed to transfer a Unicode character from one computer to another.

    Syntax

    utf8_encode(string)

    Parameter Values

    ParameterDescription
    stringRequired. Specifies the ISO-8859-1 string to encode

    Technical Details

    Return Value: The encoded string on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    On error, return the XML parser error description, line number and column number: <?php // Invalid xml file $xmlfile = 'test.xml'; $xmlparser = xml_parser_create(); // Open the file and read data $fp = fopen($xmlfile, 'r'); while ($xmldata = fread($fp, 4096)) { // parse the data chunk if (!xml_parse($xmlparser,$xmldata,feof($fp))) { die( print "ERROR: " . xml_error_string(xml_get_error_code($xmlparser)) . "<br>Line: " . xml_get_current_line_number($xmlparser) . "<br>Column: " . xml_get_current_column_number($xmlparser) . "<br>"); } } xml_parser_free($xmlparser); ?> The output of the code above could be: ERROR: Mismatched tag Line: 5 Column: 41

    Definition and Usage

    The xml_error_string() function returns the XML parser error description.

    Syntax

    xml_error_string(code)

    Parameter Values

    ParameterDescription
    codeRequired. Specifies an error code from the xml_get_error_code() function

    Technical Details

    Return Value: The error description on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    On error, return the XML parser error description, line number, column number and byte index: <?php // Invalid xml file $xmlfile = 'test.xml'; $xmlparser = xml_parser_create(); // Open the file and read data $fp = fopen($xmlfile, 'r'); while ($xmldata = fread($fp, 4096)) { // parse the data chunk if (!xml_parse($xmlparser,$xmldata,feof($fp))) { die( print "ERROR: " . xml_error_string(xml_get_error_code($xmlparser)) . "<br>Line: " . xml_get_current_line_number($xmlparser) . "<br>Column: " . xml_get_current_column_number($xmlparser) . "<br>Byte Index: " . xml_get_current_byte_index($xmlparser) . "<br>"); } } xml_parser_free($xmlparser); ?> The output of the code above could be: ERROR: Mismatched tag Line: 5 Column: 41Byte Index: 72

    Definition and Usage

    The xml_get_current_byte_index() function returns the byte index for an XML parser.

    Syntax

    xml_get_current_byte_index(parser)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use

    Technical Details

    Return Value: The current byte index on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    On error, return the XML parser error description, line number and column number: <?php // Invalid xml file $xmlfile = 'test.xml'; $xmlparser = xml_parser_create(); // Open the file and read data $fp = fopen($xmlfile, 'r'); while ($xmldata = fread($fp, 4096)) { // parse the data chunk if (!xml_parse($xmlparser,$xmldata,feof($fp))) { die( print "ERROR: " . xml_error_string(xml_get_error_code($xmlparser)) . "<br>Line: " . xml_get_current_line_number($xmlparser) . "<br>Column: " . xml_get_current_column_number($xmlparser) . "<br>"); } } xml_parser_free($xmlparser); ?> The output of the code above could be: ERROR: Mismatched tag Line: 5 Column: 41

    Definition and Usage

    The xml_get_current_column_number() function returns the current column number for an XML parser.

    Syntax

    xml_get_current_column_number(parser)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use

    Technical Details

    Return Value: The current column number on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    On error, return the XML parser error description, line number and column number: <?php // Invalid xml file $xmlfile = 'test.xml'; $xmlparser = xml_parser_create(); // Open the file and read data $fp = fopen($xmlfile, 'r'); while ($xmldata = fread($fp, 4096)) { // parse the data chunk if (!xml_parse($xmlparser,$xmldata,feof($fp))) { die( print "ERROR: " . xml_error_string(xml_get_error_code($xmlparser)) . "<br>Line: " . xml_get_current_line_number($xmlparser) . "<br>Column: " . xml_get_current_column_number($xmlparser) . "<br>"); } } xml_parser_free($xmlparser); ?> The output of the code above could be: ERROR: Mismatched tag Line: 5 Column: 41

    Definition and Usage

    The xml_get_current_line_number() function returns the current line number for an XML parser.

    Syntax

    xml_get_current_line_number(parser)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use

    Technical Details

    Return Value: The current line number on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    On error, return the XML parser error code, line number and column number: <?php // Invalid xml file $xmlfile = 'test.xml'; $xmlparser = xml_parser_create(); // Open the file and read data $fp = fopen($xmlfile, 'r'); while ($xmldata = fread($fp, 4096)) { // parse the data chunk if (!xml_parse($xmlparser,$xmldata,feof($fp))) { die( print "ERROR: " . xml_get_error_code($xmlparser) . "<br>Line: " . xml_get_current_line_number($xmlparser) . "<br>Column: " . xml_get_current_column_number($xmlparser) . "<br>"); } } xml_parser_free($xmlparser); ?> The output of the code above could be: ERROR: 76 Line: 5 Column: 41

    Definition and Usage

    The xml_get_error_code() function returns the XML parser error code.

    Syntax

    xml_get_error_code(parser)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use

    Technical Details

    Return Value: The error code on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser and parse an XML document (note.xml): <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;} xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_parse() function parses an XML document. Tip: To create an XML parser, use the xml_parser_create() function.

    Syntax

    xml_parse(parser, data, end)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    dataRequired. Specifies the data to parse
    endOptional. If set to TRUE, the data in the data parameter is the last piece of data sent in this parse. Note: Entity errors are reported at the end of the parse - and will only show if the end parameter is TRUE

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+

    More Examples

    Example

    Using the same XML file but displaying the XML data in another way: <?php $parser=xml_parser_create();function start($parser,$element_name,$element_attrs) {switch($element_name) {case "NOTE":echo "NOTE<br>";break; case "TO":echo "To: ";break;case "FROM":echo "From: "; break;case "HEADING":echo "Heading: ";break;case "BODY": echo "Message: ";}}function stop($parser,$element_name) { echo "<br>";}function char($parser,$data) {echo $data;} xml_set_element_handler($parser,"start","stop"); xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) {xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser); fclose($fp); ?> Run Example » PHP XML Parser Reference PHP XML Parser Reference

    Example

    Parse XML data into an array (from note.xml): <?php$xmlparser = xml_parser_create();$fp = fopen("note.xml", "r");$xmldata = fread($fp, 4096);// Parse XML data into an array xml_parse_into_struct($xmlparser,$xmldata,$values);xml_parser_free($xmlparser); print_r($values);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_parse_into_struct() function parses XML data into an array. This function parses the XML data into 2 arrays:
  • Value array - containing the data from the parsed XML
  • Index array - containing pointers to the location of the values in the Value array
  • Syntax

    xml_parse_into_struct(parser, data, values, index)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    dataRequired. Specifies the XML data to parse
    valuesRequired. Specifies an array with the values of the XML data
    indexOptional. Specifies an array with pointers to the location of the values in values

    Technical Details

    Return Value: 1 on success. 0 on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser with namespace support: <?php// Create an XML parser with namespace support$parser=xml_parser_create_ns(); xml_parser_free($parser);?>

    Definition and Usage

    The xml_parser_create_ns() function creates an XML parser with namespace support. Tip: To free the xml parser, use the xml_parser_free() function. Tip: To create an XML parser without namespace support, use the xml_parser_create() function instead.

    Syntax

    xml_parser_create(encoding, separator)

    Parameter Values

    ParameterDescription
    encodingOptional. Specifies the character encoding for input/output in PHP 4. From PHP 5 it specifies the character encoding only for output. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1. From PHP 5.0.2, the default output charset is UTF-8. The possible values are ISO-8859-1, UTF-8 and US-ASCII
    separatorOptional. Specifies the output separator for tag name and namespace. Default is " : "

    Technical Details

    Return Value: A resource handle to be used by other XML functions on success. FALSE on failure
    PHP Version: 4.0.5+
    Complete PHP XML Reference PHP XML Parser Reference

    Example

    Create an XML parser and parse an XML document (note.xml): <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;} xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_parser_create() function creates an XML parser. Tip: To free the xml parser, use the xml_parser_free() function. Tip: To create an XML parser with namespace support, use the xml_parser_create_ns() function instead.

    Syntax

    xml_parser_create(encoding)

    Parameter Values

    ParameterDescription
    encodingOptional. Specifies the character encoding for input/output in PHP 4. From PHP 5 it specifies the character encoding only for output. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1. From PHP 5.0.2, the default output charset is UTF-8

    Technical Details

    Return Value: A resource handle to be used by other XML functions on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, parse an XML document (note.xml), then free the XML parser: <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;} xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}// Free XML parserxml_parser_free($parser);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_parser_free() function frees an XML parser. Tip: To create an XML parser use the xml_parser_create() function.

    Syntax

    xml_parser_free(parser)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to free

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Get options from an XML parser: <?php$parser=xml_parser_create(); echo "XML_OPTION_CASE_FOLDING: " . xml_parser_get_option($parser, XML_OPTION_CASE_FOLDING) . <br>;echo "XML_OPTION_TARGET_ENCODING: " . xml_parser_get_option($parser, XML_OPTION_TARGET_ENCODING); xml_parser_free($parser);?> Run Example »

    Definition and Usage

    The xml_parser_get_option() function gets options from an XML parser.

    Syntax

    xml_parser_get_option(parser, option)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    optionRequired. Specifies the option to get. Possible values:
  • XML_OPTION_CASE_FOLDING - Specifies if case-folding is enabled. Can be 1 (TRUE) or 0 (FALSE). 1 is default
  • XML_OPTION_TARGET_ENCODING - Specifies the target encoding in this XML parser. Set to the same as the xml_parser_create() function by default (ISO-8859-1, US-ASCII or UTF-8)
  • XML_OPTION_SKIP_TAGSTART - Specifies how many characters that is skipped in the beginning of a tag name
  • XML_OPTION_SKIP_WHITE - Specifies whether values consisting of whitespace characters are skipped. Can be 1 (TRUE) or 0 (FALSE)
  • Technical Details

    Return Value: The option's value on success. FALSE and an error on failure
    PHP Version: 4.0+
    PHP Changelog: PHP 7.1: Added XML_OPTION_SKIP_TAGSTART and XML_OPTION_SKIP_WHITE to the option parameter
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Set an option in the XML parser: <?php$parser=xml_parser_create(); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_free($parser);?>

    Definition and Usage

    The xml_parser_set_option() function sets options in an XML parser.

    Syntax

    xml_parser_set_option(parser, option, value)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    optionRequired. Specifies the option to set. Possible values:
  • XML_OPTION_CASE_FOLDING - Specifies if case-folding is enabled. Can be 1 (TRUE) or 0 (FALSE). 1 is default
  • XML_OPTION_SKIP_TAGSTART - Specifies how many characters should be skipped in the beginning of a tag name
  • XML_OPTION_SKIP_WHITE - Specifies whether to skip values consisting of whitespace characters. Can be 1 (TRUE) or 0 (FALSE)
  • XML_OPTION_TARGET_ENCODING - Specifies the target encoding in this XML parser. Set to the same as the xml_parser_create() function by default (ISO-8859-1, US-ASCII or UTF-8)
  • valueRequired. Specifies options new value

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set character data handler, and parse an XML document (note.xml): <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;}// Set the character data handler xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_set_character_data_handler() function sets the character data handler for the XML parser. This function specifies what function to be called when the parser finds character data in the XML file. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_character_data_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must have two parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $data - A variable containing the character data from the XML file as a string
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set default data handler, and parse an XML document (note.xml): <?php// Create an XML parser$parser=xml_parser_create(); function def($parser,$data) {echo $data;}// Set the default data handler xml_set_default_handler($parser,"def");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_set_default_handler() function sets the default data handler for the XML parser. This function specifies what function to be called whenever the parser finds data in the XML file. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_default_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must have two parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $data - A variable containing the character data from the XML file as a string
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Specify functions to be called at the start and end of an element in the XML document (note.xml): <?php $parser=xml_parser_create();function start($parser,$element_name,$element_attrs) { switch($element_name) { case "NOTE": echo "NOTE<br>"; break; case "TO": echo "To: "; break; case "FROM": echo "From: "; break; case "HEADING": echo "Heading: "; break; case "BODY": echo "Message: "; }}function stop($parser,$element_name) { echo "<br>";}function char($parser,$data) {echo $data;} // Specify functions to be called at the start and end of an element in the XML documentxml_set_element_handler($parser,"start","stop"); xml_set_character_data_handler($parser,"char");$fp=fopen("note.xml","r"); while ($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser); fclose($fp); ?> Run Example »

    Definition and Usage

    The xml_set_element_handler() function specifies functions to be called at the start and end of an element in the XML document. Note: The start and end parameters can also be an array containing an object reference and a method name.

    Syntax

    xml_set_element_handler(parser, start, end)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    startRequired. Specifies a function to be called at the start of an element. The function must have three parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $name - A variable containing the name of the elements, that triggers this function, from the XML file as a string
  • $data - An array containing the elements attributes from the XML file as a string
  • endRequired. Specifies a function to be called at the end of an element. The function must have two parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $name - A variable containing the name of the elements, that triggers this function, from the XML file as a string
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Definition and Usage

    The xml_set_end_namespace_decl_handler() function sets up the end namespace declaration handler. This function specifies what function to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_end_namespace_decl_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must have two parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $prefix - A variable containing a string used to reference the namespace within an XML object
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0.5+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set character data handler, set external entity reference handler, and parse an XML document: <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;}function ext_ent_handler($parser,$ent,$base,$sysID,$pubID) { echo "$ent<br>"; echo "$sysID<br>"; echo "$pubID<br>"; } // Set the character data handler xml_set_character_data_handler($parser,"char");// Set the external entity reference handlerxml_set_external_entity_ref_handler($parser, "ext_ent_handler");$fp=fopen("note_entity.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?>

    Definition and Usage

    The xml_set_external_entity_ref_handler() function specifies a function to be called when the parser finds an external entity in the XML document. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_external_entity_ref_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must accept five parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $name - A variable containing the name of the external entity
  • $base - The base for resolving the system identifier (system_id) of the external entity. Currently, this is always an empty string
  • $system_id - The system identifier as specified in the entity declaration
  • $public_id - The public identifier as specified in the entity declaration
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set character data handler, set notation declaration handler, and parse an XML document: <?php// Create an XML parser$parser=xml_parser_create(); function char($parser,$data) {echo $data;}function not_decl_handler($parser,$not,$base,$sysID,$pubID) { echo "$not<br>"; echo "$sysID<br>"; echo "$pubID<br>"; } // Set the character data handler xml_set_character_data_handler($parser,"char");// Set the notation declaration handlerxml_set_notation_decl_handler($parser, "not_decl_handler");$fp=fopen("note_notation.xml","r"); while ($data=fread($fp,4096)) { // Parse XML data xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));}xml_parser_free($parser);fclose($fp); ?>

    Definition and Usage

    The xml_set_notation_decl_handler() function specifies a function to be called when the parser finds a notation declaration in the XML document. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_notation_decl_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must accept five parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $name - A variable containing the name of the notation
  • $base - The base for resolving the system identifier (system_id) of the external entity. Currently, this is always an empty string
  • $system_id - The system identifier of the external notation declaration
  • $public_id - The public identifier of the external notation declaration
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Use XML parser within an object: <?phpclass XMLParser{private $parser;function __construct() { $this->parser = xml_parser_create(); xml_set_object($this->parser, $this); xml_set_element_handler($this->parser, "start_tag", "end_tag"); xml_set_character_data_handler($this->parser, "cdata");}function __destruct() { xml_parser_free($this->parser); unset($this->parser);}function parse($data) { xml_parse($this->parser, $data); } function start_tag($parser, $tag, $attributes) { var_dump($tag, $attributes); }function cdata($parser, $cdata) { var_dump($cdata);}function end_tag($parser, $tag) { var_dump($tag);}} $xml_parser = new XMLParser();$xml_parser->parse("<p id='test'>Hello World!</p>");?> Run Example »

    Definition and Usage

    The xml_set_object() function allows a XML parser to be used within an object.

    Syntax

    xml_set_object(parser, object)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    objectRequired. Specifies the object where to use the XML parser

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set character data handler, set PI handler, and parse an XML document (note_pi.xml): <?php$parser=xml_parser_create(); function char($parser,$data) { echo $data; } function pi_handler($parser, $target, $data) { echo "Target: $target<br />"; echo "Data: $data<br />"; } xml_set_character_data_handler($parser,"char");// Set up PI handler xml_set_processing_instruction_handler($parser, "pi_handler"); $fp=fopen("note_pi.xml","r"); while ($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } xml_parser_free($parser); ?> Run Example »

    Definition and Usage

    The xml_set_processing_instruction_handler() function specifies a function to be called when the parser finds a processing instruction (PI) in the XML document. A PI is enclosed in <? and ?> and contains a a target followed by data. Example: In this case the PI associates a style sheet with an XML document: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="default.xsl" type="text/xml"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_processing_instruction_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must accept three parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $target - A variable containing the PI target
  • $data - A variable containing the PI data
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference PHP XML Parser Reference

    Definition and Usage

    The xml_set_start_namespace_decl_handler() function sets up the start namespace declaration handler. This function specifies what function to be called when a namespace is declared. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_start_namespace_decl_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be used as an event handler. The function must have three parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $prefix - A variable containing a reference to the namespace within an XML object
  • $uri - The URI of the namspace
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0.5+
    PHP XML Parser Reference PHP XML Parser Reference

    Example

    Create an XML parser, set character data handler, set unparsed entity declaration handler, and parse an XML document: <?php$parser=xml_parser_create(); function char($parser,$data) { echo $data; } function unparsed_ent_handler($parser,$entname,$base,$sysID,$pubID,$notname) { print "$entname<br>"; print "$sysID<br>"; print "$pubID<br>"; print "$notname<br>"; } xml_set_character_data_handler($parser,"char");// Set up unparsed entity declaration handler xml_set_unparsed_entity_decl_handler($parser,"unparsed_ent_handler"); $fp=fopen("test.xml","r"); while ($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } xml_parser_free($parser);fclose($fp); ?>

    Definition and Usage

    The xml_set_unparsed_entity_decl_handler() function specifies a function to be called when the parser an unparsed entity in the XML document. Note: The handler parameter can also be an array containing an object reference and a method name.

    Syntax

    xml_set_unparsed_entity_decl_handler(parser, handler)

    Parameter Values

    ParameterDescription
    parserRequired. Specifies the XML parser to use
    handlerRequired. Specifies a function to be called if the XML parser encounters an external entity declaration with an NDATA declaration. The function must accept six parameters:
  • $parser - A variable containing the XML parser calling the handler
  • $entity_name - A variable containing the name of the entity
  • $base - The base for resolving the system identifier (system_id) of the external entity. Currently, this is always an empty string
  • $system_id - The system identifier of the external entity
  • $public_id - The public identifier of the external entity
  • $notation_name - The name of the notation of this entity
  • Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.0+
    PHP XML Parser Reference

    Zip Introduction

    The Zip files functions allows you to read ZIP files.

    Requirements

    The ZIP extension requires libzip.

    Installation

    Linux Systems For these functions to work, you have to compile PHP with --enable-zip. PHP 5.6: Use the --with-libzip=DIR configure option to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended. PHP 7.3: Building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration. Windows Systems Before PHP 5.3: Users must enable "php_zip.dll" inside of "php.ini" for these functions to work. From PHP 5.3: The ZIP extension is built-in.

    Zip Functions

    FunctionDescription
    zip_close()Closes a ZIP file archive
    zip_entry_close()Closes a ZIP directory entry
    zip_entry_compressedsize()Returns the compressed file size of a ZIP directory entry
    zip_entry_compressionmethod()Returns the compression method of a ZIP directory entry
    zip_entry_filesize()Returns the actual file size of a ZIP directory entry
    zip_entry_name()Returns the name of a ZIP directory entry
    zip_entry_open()Opens a directory entry in a ZIP file for reading
    zip_entry_read()Reads from an open directory entry in the ZIP file
    zip_open()Opens a ZIP file archive
    zip_read()Reads the next file in a open ZIP file archive
    PHP Zip Reference

    Example

    Open, read, and close a ZIP file archive: <?php $zip = zip_open("test.zip"); zip_read($zip); // some code zip_close($zip); ?>

    Definition and Usage

    The zip_close() function closes a ZIP file archive opened by the zip_open() function.

    Syntax

    zip_close(zip)

    Parameter Values

    ParameterDescription
    zipRequired. Specifies the ZIP file to close (opened with zip_open() )

    Technical Details

    Return Value: Nothing
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Close a ZIP directory entry opened by zip_entry_open(): <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { if (zip_entry_open($zip, $zip_entry)) { // some code // Close directory entry zip_entry_close($zip_entry); } } zip_close($zip); } ?>

    Definition and Usage

    The zip_entry_close() function closes a ZIP directory entry opened by zip_entry_open().

    Syntax

    zip_entry_close(zip_entry)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the ZIP directory entry returned by zip_read()

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive and get the name and compressed size of the directory entries: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>"; // Get name of directory entry echo "Name: " . zip_entry_name($zip_entry) . "<br>"; // Get compressed size echo "Compressed size: " . zip_entry_compressedsize($zip_entry); echo "</p>"; } zip_close($zip); } ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt Compressed size: 56 Name: htmlziptest.html Compressed size: 101

    Definition and Usage

    The zip_entry_compressedsize() function returns the compressed file size of a ZIP directory entry.

    Syntax

    zip_entry_compressedsize(zip_entry)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the ZIP directory entry returned by zip_read()

    Technical Details

    Return Value: The compressed size
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive and get the name and compression method of the directory entries: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>"; // Get name of directory entry echo "Name: " . zip_entry_name($zip_entry) . "<br>"; // Get compression method echo "Compression method: " . zip_entry_compressionmethod($zip_entry); echo "</p>"; } zip_close($zip); } ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt Compression method: deflated Name: htmlziptest.html Compression method: deflated

    Definition and Usage

    The zip_entry_compressionmethod() function returns the compression method of a ZIP directory entry.

    Syntax

    zip_entry_compressionmethod(zip_entry)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the ZIP directory entry returned by zip_read()

    Technical Details

    Return Value: The compression method
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive and get the name and file size of the directory entries: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>"; // Get name of directory entry echo "Name: " . zip_entry_name($zip_entry) . "<br>"; // Get filesize of directory entry echo "Filesize: " . zip_entry_filesize($zip_entry); echo "</p>"; } zip_close($zip); } ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt Filesize: 59 Name: htmlziptest.html Filesize: 124

    Definition and Usage

    The zip_entry_filesize() function returns the actual file size of a ZIP directory entry.

    Syntax

    zip_entry_filesize(zip_entry)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the ZIP directory entry returned by zip_read()

    Technical Details

    Return Value: The size of the directory entry
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive and get the names of the directory entries: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { // Get name of directory entry echo "Name: " . zip_entry_name($zip_entry) . "<br>"; } zip_close($zip); } ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt Name: htmlziptest.html

    Definition and Usage

    The zip_entry_name() function returns the name of a ZIP directory entry.

    Syntax

    zip_entry_name(zip_entry)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the zip directory entry returned by zip_read()

    Technical Details

    Return Value: The name of the directory entry
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive, open directory entry for reading, and read from the open directory entry: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>Name: " . zip_entry_name($zip_entry) . "<br>"; // Open directory entry for reading if (zip_entry_open($zip, $zip_entry)) { echo "File Contents:<br>"; // Read open directory entry $contents = zip_entry_read($zip_entry); echo "$contents<br>"; zip_entry_close($zip_entry); } echo "</p>"; } zip_close($zip);} ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt File Contents: Hello World! This is a test. Name: htmlziptest.html File Contents:

    Hello World!

    This is a test for the zip functions in PHP.

    Definition and Usage

    The zip_entry_open() function opens a directory entry in a ZIP file for reading.

    Syntax

    zip_entry_open(zip, zip_entry, mode)

    Parameter Values

    ParameterDescription
    zipRequired. Specifies the ZIP resource opened with zip_open()
    zip_entryRequired. Specifies the ZIP directory entry to open (opened with zip_read())
    modeOptional. Specifies the type of access you require to the ZIP archive. Note: Currently, mode is always "rb", because ZIP support in PHP is read only

    Technical Details

    Return Value: TRUE on success. FALSE on failure
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open a ZIP file archive, open directory entry for reading, and read from the open directory entry: <?php $zip = zip_open("test.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "<p>Name: " . zip_entry_name($zip_entry) . "<br>"; // Open directory entry for reading if (zip_entry_open($zip, $zip_entry)) { echo "File Contents:<br>"; // Read open directory entry $contents = zip_entry_read($zip_entry); echo "$contents<br>"; zip_entry_close($zip_entry); } echo "</p>"; } zip_close($zip);} ?> The output of the code depends on the contents of the ZIP archive: Name: ziptest.txt File Contents: Hello World! This is a test. Name: htmlziptest.html File Contents:

    Hello World!

    This is a test for the zip functions in PHP.

    Definition and Usage

    The zip_entry_read() function reads from an open directory entry.

    Syntax

    zip_entry_read(zip_entry, length)

    Parameter Values

    ParameterDescription
    zip_entryRequired. Specifies the directory entry returned by zip_read()
    lengthOptional. Specifies the number of (uncompressed) bytes to return. Default is 1024

    Technical Details

    Return Value: The data read or " on end of file. FALSE on failure
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open, read, and close a ZIP file archive: <?php $zip = zip_open("test.zip"); zip_read($zip); // some code zip_close($zip); ?>

    Definition and Usage

    The zip_open() function opens a ZIP file archive.

    Syntax

    zip_open(zip)

    Parameter Values

    ParameterDescription
    zipRequired. Specifies the ZIP file to open

    Technical Details

    Return Value: A resource handle on success. FALSE on failure
    PHP Version: 4.1.0+
    PHP Zip Reference PHP Zip Reference

    Example

    Open, read, and close a ZIP file archive: <?php $zip = zip_open("test.zip"); zip_read($zip); // some code zip_close($zip); ?>

    Definition and Usage

    The zip_read() function reads the next file in a open ZIP file archive. Tip: The resource returned by zip_read() can be used by the zip_entry_*() functions.

    Syntax

    zip_read(zip)

    Parameter Values

    ParameterDescription
    zipRequired. Specifies a ZIP file opened with zip_open()

    Technical Details

    Return Value: A resource containing a file within the ZIP archive on success. FALSE if there is no more entries to read or on failure
    PHP Version: 4.1.0+
    PHP Zip Reference

    Supported Timezones

    Below is a complete list of the timezones supported by PHP, which are useful with several PHP date functions.
  • Africa
  • America
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Indian
  • Pacific
  • Africa

    Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara
    Africa/AsmeraAfrica/BamakoAfrica/BanguiAfrica/BanjulAfrica/Bissau
    Africa/BlantyreAfrica/BrazzavilleAfrica/BujumburaAfrica/CairoAfrica/Casablanca
    Africa/CeutaAfrica/ConakryAfrica/DakarAfrica/Dar_es_SalaamAfrica/Djibouti
    Africa/DoualaAfrica/El_AaiunAfrica/FreetownAfrica/GaboroneAfrica/Harare
    Africa/JohannesburgAfrica/JubaAfrica/KampalaAfrica/KhartoumAfrica/Kigali
    Africa/KinshasaAfrica/LagosAfrica/LibrevilleAfrica/LomeAfrica/Luanda
    Africa/LubumbashiAfrica/LusakaAfrica/MalaboAfrica/MaputoAfrica/Maseru
    Africa/MbabaneAfrica/MogadishuAfrica/MonroviaAfrica/NairobiAfrica/Ndjamena
    Africa/NiameyAfrica/NouakchottAfrica/OuagadougouAfrica/Porto-NovoAfrica/Sao_Tome
    Africa/TimbuktuAfrica/TripoliAfrica/TunisAfrica/Windhoek

    America

    America/Adak America/Anchorage America/Anguilla
    America/AntiguaAmerica/AraguainaAmerica/Argentina/Buenos_Aires
    America/Argentina/CatamarcaAmerica/Argentina/ComodRivadaviaAmerica/Argentina/Cordoba
    America/Argentina/JujuyAmerica/Argentina/La_RiojaAmerica/Argentina/Mendoza
    America/Argentina/Rio_GallegosAmerica/Argentina/SaltaAmerica/Argentina/San_Juan
    America/Argentina/San_LuisAmerica/Argentina/TucumanAmerica/Argentina/Ushuaia
    America/ArubaAmerica/AsuncionAmerica/Atikokan
    America/AtkaAmerica/BahiaAmerica/Bahia_Banderas
    America/BarbadosAmerica/BelemAmerica/Belize
    America/Blanc-SablonAmerica/Boa_VistaAmerica/Bogota
    America/BoiseAmerica/Buenos_AiresAmerica/Cambridge_Bay
    America/Campo_GrandeAmerica/CancunAmerica/Caracas
    America/CatamarcaAmerica/CayenneAmerica/Cayman
    America/ChicagoAmerica/ChihuahuaAmerica/Coral_Harbour
    America/CordobaAmerica/Costa_RicaAmerica/Creston
    America/CuiabaAmerica/CuracaoAmerica/Danmarkshavn
    America/DawsonAmerica/Dawson_CreekAmerica/Denver
    America/DetroitAmerica/DominicaAmerica/Edmonton
    America/EirunepeAmerica/El_SalvadorAmerica/Ensenada
    America/Fort_WayneAmerica/FortalezaAmerica/Glace_Bay
    America/GodthabAmerica/Goose_BayAmerica/Grand_Turk
    America/GrenadaAmerica/GuadeloupeAmerica/Guatemala
    America/GuayaquilAmerica/GuyanaAmerica/Halifax
    America/HavanaAmerica/HermosilloAmerica/Indiana/Indianapolis
    America/Indiana/KnoxAmerica/Indiana/MarengoAmerica/Indiana/Petersburg
    America/Indiana/Tell_CityAmerica/Indiana/VevayAmerica/Indiana/Vincennes
    America/Indiana/WinamacAmerica/IndianapolisAmerica/Inuvik
    America/IqaluitAmerica/JamaicaAmerica/Jujuy
    America/JuneauAmerica/Kentucky/LouisvilleAmerica/Kentucky/Monticello
    America/Knox_INAmerica/KralendijkAmerica/La_Paz
    America/LimaAmerica/Los_AngelesAmerica/Louisville
    America/Lower_PrincesAmerica/MaceioAmerica/Managua
    America/ManausAmerica/MarigotAmerica/Martinique
    America/MatamorosAmerica/MazatlanAmerica/Mendoza
    America/MenomineeAmerica/MeridaAmerica/Metlakatla
    America/Mexico_CityAmerica/MiquelonAmerica/Moncton
    America/MonterreyAmerica/MontevideoAmerica/Montreal
    America/MontserratAmerica/NassauAmerica/New_York
    America/NipigonAmerica/NomeAmerica/Noronha
    America/North_Dakota/BeulahAmerica/North_Dakota/CenterAmerica/North_Dakota/New_Salem
    America/OjinagaAmerica/PanamaAmerica/Pangnirtung
    America/ParamariboAmerica/PhoenixAmerica/Port-au-Prince
    America/Port_of_SpainAmerica/Porto_AcreAmerica/Porto_Velho
    America/Puerto_RicoAmerica/Rainy_RiverAmerica/Rankin_Inlet
    America/RecifeAmerica/ReginaAmerica/Resolute
    America/Rio_BrancoAmerica/RosarioAmerica/Santa_Isabel
    America/SantaremAmerica/SantiagoAmerica/Santo_Domingo
    America/Sao_PauloAmerica/ScoresbysundAmerica/Shiprock
    America/SitkaAmerica/St_BarthelemyAmerica/St_Johns
    America/St_KittsAmerica/St_LuciaAmerica/St_Thomas
    America/St_VincentAmerica/Swift_CurrentAmerica/Tegucigalpa
    America/ThuleAmerica/Thunder_BayAmerica/Tijuana
    America/TorontoAmerica/TortolaAmerica/Vancouver
    America/VirginAmerica/WhitehorseAmerica/Winnipeg
    America/YakutatAmerica/Yellowknife

    Antarctica

    Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie Antarctica/Mawson
    Antarctica/McMurdoAntarctica/PalmerAntarctica/RotheraAntarctica/South_PoleAntarctica/Syowa
    Antarctica/Vostok

    Arctic

    Arctic/Longyearbyen

    Asia

    Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau
    Asia/AqtobeAsia/AshgabatAsia/AshkhabadAsia/BaghdadAsia/Bahrain
    Asia/BakuAsia/BangkokAsia/BeirutAsia/BishkekAsia/Brunei
    Asia/CalcuttaAsia/ChoibalsanAsia/ChongqingAsia/ChungkingAsia/Colombo
    Asia/DaccaAsia/DamascusAsia/DhakaAsia/DiliAsia/Dubai
    Asia/DushanbeAsia/GazaAsia/HarbinAsia/HebronAsia/Ho_Chi_Minh
    Asia/Hong_KongAsia/HovdAsia/IrkutskAsia/IstanbulAsia/Jakarta
    Asia/JayapuraAsia/JerusalemAsia/KabulAsia/KamchatkaAsia/Karachi
    Asia/KashgarAsia/KathmanduAsia/KatmanduAsia/KhandygaAsia/Kolkata
    Asia/KrasnoyarskAsia/Kuala_LumpurAsia/KuchingAsia/KuwaitAsia/Macao
    Asia/MacauAsia/MagadanAsia/MakassarAsia/ManilaAsia/Muscat
    Asia/NicosiaAsia/NovokuznetskAsia/NovosibirskAsia/OmskAsia/Oral
    Asia/Phnom_PenhAsia/PontianakAsia/PyongyangAsia/QatarAsia/Qyzylorda
    Asia/RangoonAsia/RiyadhAsia/SaigonAsia/SakhalinAsia/Samarkand
    Asia/SeoulAsia/ShanghaiAsia/SingaporeAsia/TaipeiAsia/Tashkent
    Asia/TbilisiAsia/TehranAsia/Tel_AvivAsia/ThimbuAsia/Thimphu
    Asia/TokyoAsia/Ujung_PandangAsia/UlaanbaatarAsia/Ulan_BatorAsia/Urumqi
    Asia/Ust-NeraAsia/VientianeAsia/VladivostokAsia/YakutskAsia/Yekaterinburg
    Asia/Yerevan

    Atlantic

    Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe
    Atlantic/FaroeAtlantic/Jan_MayenAtlantic/MadeiraAtlantic/ReykjavikAtlantic/South_Georgia
    Atlantic/St_HelenaAtlantic/Stanley

    Australia

    Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra
    Australia/CurrieAustralia/DarwinAustralia/EuclaAustralia/HobartAustralia/LHI
    Australia/LindemanAustralia/Lord_HoweAustralia/MelbourneAustralia/NorthAustralia/NSW
    Australia/PerthAustralia/QueenslandAustralia/SouthAustralia/SydneyAustralia/Tasmania
    Australia/VictoriaAustralia/WestAustralia/Yancowinna

    Europe

    Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade
    Europe/BerlinEurope/BratislavaEurope/BrusselsEurope/BucharestEurope/Budapest
    Europe/BusingenEurope/ChisinauEurope/CopenhagenEurope/DublinEurope/Gibraltar
    Europe/GuernseyEurope/HelsinkiEurope/Isle_of_ManEurope/IstanbulEurope/Jersey
    Europe/KaliningradEurope/KievEurope/LisbonEurope/LjubljanaEurope/London
    Europe/LuxembourgEurope/MadridEurope/MaltaEurope/MariehamnEurope/Minsk
    Europe/MonacoEurope/MoscowEurope/NicosiaEurope/OsloEurope/Paris
    Europe/PodgoricaEurope/PragueEurope/RigaEurope/RomeEurope/Samara
    Europe/San_MarinoEurope/SarajevoEurope/SimferopolEurope/SkopjeEurope/Sofia
    Europe/StockholmEurope/TallinnEurope/TiraneEurope/TiraspolEurope/Uzhgorod
    Europe/VaduzEurope/VaticanEurope/ViennaEurope/VilniusEurope/Volgograd
    Europe/WarsawEurope/ZagrebEurope/ZaporozhyeEurope/Zurich

    Indian

    Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
    Indian/KerguelenIndian/MaheIndian/MaldivesIndian/MauritiusIndian/Mayotte
    Indian/Reunion

    Pacific

    Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk Pacific/Easter
    Pacific/EfatePacific/EnderburyPacific/FakaofoPacific/FijiPacific/Funafuti
    Pacific/GalapagosPacific/GambierPacific/GuadalcanalPacific/GuamPacific/Honolulu
    Pacific/JohnstonPacific/KiritimatiPacific/KosraePacific/KwajaleinPacific/Majuro
    Pacific/MarquesasPacific/MidwayPacific/NauruPacific/NiuePacific/Norfolk
    Pacific/NoumeaPacific/Pago_PagoPacific/PalauPacific/PitcairnPacific/Pohnpei
    Pacific/PonapePacific/Port_MoresbyPacific/RarotongaPacific/SaipanPacific/Samoa
    Pacific/TahitiPacific/TarawaPacific/TongatapuPacific/TrukPacific/Wake
    Pacific/WallisPacific/Yap