Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Function Explanation Example

sizeof($arr) This function returns the number Code:


of elements in an array. $data = array("red", "green", "blue");
Use this function to find out how
many elements an array contains; echo "Array has " . sizeof($data) . "
this information is most elements";
commonly used to initialize a loop ?>
counter when processing the
array. Output:
Array has 3 elements
array_values($arr) This function accepts a PHP array Code:
and returns a new array $data = array("hero" => "Holmes",
containing only its values (not its "villain" => "Moriarty");
keys). Its counterpart is the print_r(array_values($data));
array_keys() function. ?>
Use this function to retrieve all
the values from an associative Output:
array. Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr) This function accepts a PHP array Code:
and returns a new array $data = array("hero" => "Holmes",
containing only its keys (not its "villain" => "Moriarty");
values). Its counterpart is the print_r(array_keys($data));
array_values() function. ?>
Use this function to retrieve all
the keys from an associative array. Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr) This function removes an element Code:
from the end of an array. $data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val) This function adds an element to Code:
the end of an array. $data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr) This function removes an element Code:
from the beginning of an array. $data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val) This function adds an element to Code:
the beginning of an array. $data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr) This function is most often used to Code:
iteratively traverse an array. Each $data = array("hero" => "Holmes",
time each() is called, it returns the "villain" => "Moriarty");
current key-value pair and moves while (list($key, $value) = each($data)) {
the array cursor forward one echo "$key: $value \n";
element. This makes it most }
suitable for use in a loop. ?>

Output:
hero: Holmes 
villain: Moriarty
sort($arr) This function sorts the elements Code:
of an array in ascending order. $data = array("g", "t", "a", "s");
String values will be arranged in sort($data);
ascending alphabetical order. print_r($data);
Note: Other sorting functions ?>
include  asort(), arsort(), ksort(),
krsort() and rsort(). Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr) The function exchanges the keys Code:
and values of a PHP associative $data = array("a" => "apple", "b" =>
array. "ball");
Use this function if you have a print_r(array_flip($data));
tabular (rows and columns) ?>
structure in an array, and you
want to interchange the rows and Output:
columns. Array
(
 sort() - sort arrays [apple] => a
in ascending order [ball] => b
 rsort() - sort )
arrays in
descending order
 asort() - sort
associative arrays in
ascending order,
according to the
value
 ksort() - sort
associative arrays in
ascending order,
according to the key
 arsort() - sort
associative arrays in
descending order,
according to the
value
 krsort() - sort
associative arrays in
descending order,
according to the key

array_reverse($arr) The function reverses the order of Code:


elements in an array. $data = array(10, 20, 25, 60);
Use this function to re-order a print_r(array_reverse($data));
sorted list of values in reverse for ?>
easier processing—for example,
when you're trying to begin with Output:
the minimum or maximum of a Array
set of ordered values. (
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr) This function merges two or more Code:
arrays to create a single $data1 = array("cat", "goat");
composite array. Key collisions are $data2 = array("dog", "cow");
resolved in favor of the latest print_r(array_merge($data1, $data2));
entry. ?>
Use this function when you need
to combine data from two or Output:
more arrays into a single structure Array
—for example, records from two (
different SQL queries. [0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr) This function selects one or more Code:
random elements from an array. $data = array("white", "black", "red");
Use this function when you need echo "Today's color is " .
to randomly select from a $data[array_rand($data)];
collection of discrete values—for ?>
example, picking a random color
from a list. Output:
Today's color is red
array_search($search, $arr) This function searches the values Code:
in an array for a match to the $data = array("blue" => "#0000cc",
search term, and returns the "black" => "#000000", "green" =>
corresponding key if found. If "#00ff00");
more than one match exists, the echo "Found " . array_search("#0000cc",
key of the first matching value is $data);
returned. ?>
Use this function to scan a set of
index-value pairs for matches, and Output:
return the matching index. Found blue
array_slice($arr, $offset, This function is useful to extract a Code:
$length) subset of the elements of an $data = array("vanilla", "strawberry",
array, as another array. Extracting "mango", "peaches");
begins from array offset $offset print_r(array_slice($data, 1, 2));
and continues until the array slice ?>
is $length elements long.
Use this function to break a larger Output:
array into smaller ones—for Array
example, when segmenting an (
array by size ("chunking") or type [0] => strawberry
of data. [1] => mango
)
array_unique($data) This function strips an array of Code:
duplicate values. $data = array(1,1,4,6,7,4);
Use this function when you need print_r(array_unique($data));
to remove non-unique elements ?>
from an array—for example, when
creating an array to hold values Output:
for a table's primary key. Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func) This function "walks" through an Code:
array, applying a user-defined function reduceBy10(&$val, $key) {
function to every element. It $val -= $val * 0.1;
returns the changed array. }
Use this function if you need to
perform custom processing on $data = array(10,20,30,40);
every element of an array—for array_walk($data, 'reduceBy10');
example, reducing a number print_r($data);
series by 10%. ?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)

PHP 5 Array Functions


Function Description
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() 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 5 Filesystem Functions


Function Description
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() or unset()
dirname() Returns the directory name component of a path
disk_free_space() Returns the free space of a directory
disk_total_space() Returns the total size of a directory
diskfreespace() Alias of disk_free_space()
fclose() Closes an open file
feof() Tests for end-of-file on an open file
fflush() Flushes buffered output to an open file
fgetc() Returns a character from an open file
fgetcsv() Parses a line from an open file, checking for CSV fields
fgets() Returns a line from an open file
fgetss() Returns a line, with HTML and PHP tags removed, from an open file
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 a string 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 permissions of a file
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 an open 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
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
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 writeable
is_writeable() Alias of is_writable()
lchgrp() Changes group ownership of symlink
lchown() Changes user ownership of symlink
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() Sets the buffer size of an open 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
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script

$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (C


is using

$_SERVER['SERVER_ADDR'] Returns the IP address of the host server

$_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3sch

$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protoco


HTTP/1.1)

$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (suc

$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such a

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a que

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request

$_SERVER['HTTP_ACCEPT_CHARSET' Returns the Accept_Charset header from the current requ


] utf-8,ISO-8859-1)

$_SERVER['HTTP_HOST'] Returns the Host header from the current request


$_SERVER['HTTP_REFERER'] Returns the complete URL of the page from which the cur
called

$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing th

$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing th

$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to com
the web server

$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing

$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive


server configuration file (if your script runs on a virtual ho
value defined for that virtual host) (such as someone@w3

$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the
communication (such as 80)

$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which a
server-generated pages

$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script

$_SERVER['SCRIPT_NAME'] Returns the path of the current script


$_SERVER['SCRIPT_URI'] Returns the URI of the current page

You might also like