Page 1 of 163

PHP Reference: Beginner to Intermediate PHP5

PHP Reference: Beginner to

Intermediate PHP5

Mario Lurig

1

Page 2 of 163

Mario Lurig

PHP Reference: 2008

Beginner to Intermediate PHP5

ISBN: 978-1-4357-1590-5

Creative Commons Attribution-NonCommercial-ShareAlike 2.0

You are free:

to Share — to copy, distribute and transmit the work

to Remix — to adapt the work

Under the following conditions:

Attribution. You must attribute the work in the manner specified by the

author or licensor (but not in any way that suggests that they endorse you or

your use of the work).

Noncommercial. You may not use this work for commercial purposes.

Share Alike. If you alter, transform, or build upon this work, you may

distribute the resulting work only under the same or similar license to this

one.

For any reuse or distribution, you must make clear to others the license

terms of this work.

Any of the above conditions can be waived if you get permission from the

copyright holder.

Nothing in this license impairs or restricts the author's moral rights.

FIRST EDITION

http://www.phpreferencebook.com

Cover art credit (PHP REFERENCE:), included with permission:

Leo Reynolds ( www.flickr.com/lwr/ ) - 7 images

Patrick Goor ( www.labworks.eu ) - 3 images

Eva the Weaver ( www.flickr.com/evaekeblad/ ) - 2 images

Duncan Cumming ( www.flickr.com/duncan/ ) - 1 image

2

Page 3 of 163

PHP Reference: Beginner to Intermediate PHP5

Contents

Preface . . . . . . . 5

Miscellaneous Things You Should Know . . . 9

Operators . . . . . . . 19

Control Structures . . . . . . 25

Global Variables . . . . . . 33

Variable Functions . . . . . . 35

String Functions . . . . . . 41

Array Functions . . . . . . 71

Date/Time Functions . . . . . . 103

Mathematical Functions . . . . . 111

MySQL Functions . . . . . . 115

Directory & File System Functions . . . . 127

Output Control (Output Buffer) . . . . 139

Sessions . . . . . . . 145

Regular Expressions . . . . . . 149

Common Language Index . . . . . 159

Function Index . . . . . . . 161

3

Page 4 of 163

Mario Lurig

4

Page 5 of 163

PHP Reference: Beginner to Intermediate PHP5

Preface

I taught myself PHP and MySQL and found myself, at times,

without internet access and thus without search access to the PHP.net

manual ( http://www.php.net/manual/en/ ). Since coding was not my

primary job, I needed a refresher on syntax, usage, and most of all, a

reminder of how to code PHP without spending an hour debugging a silly

mistake. I printed out reference sheets, cards, cheat sheets and tried to work

off of them exclusively. However, I still found myself needing more than

would fit on one page of 8.5" x 11" paper front and back. So, off I went to the

web and the local bookstore. After spending some time with a few books,

giving them a trial run, I ran into two major problems:

1. I spent most of the time weeding through extensive tutorials to find

the keyword and answer I was looking for, sometimes fruitlessly.

2. Information was biased or surrounded by irrelevant and often

confusing code that did little to explain the what of the function.

I figured I couldn't be the only one with this problem, and quickly

found out that I wasn't alone thanks to a chance run-in at a local bookstore.

Casual PHP programmers, sometimes away from the internet, wanting a

quick reference book that assumes they have some experience with PHP and

understood the basics while still needing a little clarification sometimes on

the details. Therefore, this book was born.

For this edition, I decided to eliminate some of the more advanced

aspects of PHP programming: object oriented programming, image

manipulation/creation, secondary modules, and a few others. Secondarily,

items such as mail handling, file manipulation, regular expressions, MySQL,

sessions, and cookies were balanced for complexity and usability, usually

excluding the more advanced uses, such as streams . Finally, this book is not

an exhaustive collection of every PHP function, but a majority selection of

those appropriate for beginner to intermediate programmers. The most

common or effective functions are included and some aliases are left out to

reduce confusion, such as including is_int() and not is_long().

5

Page 6 of 163

Mario Lurig

A few bits of nomenclature should be addressed and provided, to

better understand the word/code used inside this book. In other words, here

are some assumptions made inside this book that you should understand:

expr – An expression (e.g. $x == 1), including boolean

$variable – A string, integer, float, array or boolean1

$scalar - A string, integer, float, or boolean

$string – A string variable or its equivalent ( e.g. "string" or 'string' )

$array – An array variable or its equivalent ( e.g. array( 'one' , 'two' , 'three' ) )

key – Represents the key (integer or string) of an array ( e.g. $array[key] )

value – In relation to an array, represents the $variable value ( e.g.

array( 'value ') )

This book also shows all code using procedural PHP and standard

syntax. However, you will find many tips will include the alternative syntax

for control structures as to better allow you, the reader, to choose whichever

you would prefer. Here is an example of both:

// Standard syntax

if ($x == 1) {

echo 'Hello World!';

} else {

echo 'Goodbye World!';

}

// Alternative syntax

if ($x == 1):

echo 'Hello World!';

else:

echo 'Goodbye World!';

endif;

Furthermore, the use of whitespace and indenting is for clarity and is

completely up to your preference. Styles vary greatly in the community, so

please be aware that the use of spaces or whitespace does not directly affect

the PHP code.

The majority of the book is a collection of functions, their

descriptions, example code, maybe an extra tip, and some related functions

that may be of interest. All sample code will be accompanied by the sample

output, and the output will have a gray background. The definition and

example section is separated from the extraneous tip section by the use of

three black clovers, centered on the line. It is meant as a simple visual clue to

keep one from getting distracted or lost and confusing the next bit of

information as required reading. All functions will be presented using the

following formatting:

1 Boolean is usually used within an expression. While it is also evaluated as a variable, output

results may vary and are noted within specific functions whenever possible

6

Page 7 of 163

PHP Reference: Beginner to Intermediate PHP5

function name(input, [optional input])

Description/definition

Example:

Code with // comments

Output of code as seen through a web browser's output

See Also:

function – simplified and relevant definition

function – simplified and relevant definition

♣ ♣ ♣

Thanks, and enjoy the show!

7

{Optional Section} Tip to help with usage or trick on using it

Extra code

related to the tip

Output

{

[0] => Of

[1] => Code

}

Page 8 of 163

Mario Lurig

8

Page 9 of 163

PHP Reference: Beginner to Intermediate PHP5

Miscellaneous Things You Should Know

Not everything fits into a neat little category, nor does everything in

PHP belong in this reference book. However, sometimes they deserve a

quick note and a little attention and shall be included here.

PHP Code

For portability and compatibility, always use the long form.

Long form:

<?php expr ?>

Short form:

<? expr ?>

Short form equivalent of <? echo expr ?>

Note: No closing semicolon (;) is required.

<?= expr ?>

Semicolon ( ; )

All statements must end in a semicolon ( ; )! Otherwise, errors will be

generated. If the error doesn't make sense, you probably are missing a

semicolon somewhere!

Quotations

' ' (single quotes) – Content inside single quotes is evaluated literally.

Therefore, $string actually means: (dollar sign)string, and does not represent

the variable's value.

Example:

$string = 'Single Quotes';

echo '$string';

$string

9

Page 16 of 163

Mario Lurig

get_magic_quotes_gpc()

Returns 0 if it is off, 1 otherwise.

Used to determine if magic quotes is on. This check is used for code

portability and determining if the addition of backslashes is necessary for

security purposes and preventing SQL injection. Magic_quotes_gpc

processes GET/POST/Cookie data and, if turned on, automatically processes

the above data every time with addslashes().

Example:

if (get_magic_quotes_gpc()){

echo 'Magic Quotes is on!';

}else{

echo 'Magic Quotes is NOT on, use addslashes()!';

}

// This is the default setting for PHP5 installations

Magic Quotes is NOT on, use addslashes()!

See Also:

addslashes() – Add backslashes to certain special characters in a string

stripslashes() – Remove backslashes from certain special characters in a

string

phpinfo([option])

option – [optional] Used with a specific $integer or $string to display only a

portion of phpinfo(). Specific options excluded for simplicity.

By default, phpinfo() will display everything about the PHP installation,

including the modules, version, variables, etc.

Example:

phpinfo();

Display All PHP Errors and Warnings

To catch programming errors, mistakes, or make sure that PHP is not

making any assumptions about your code, troubleshooting is best done with

all PHP errors being displayed. The following two lines of code will enable

this mode:

error_reporting(E_ALL);

ini_set('display_errors', '1');

16

Page 17 of 163

PHP Reference: Beginner to Intermediate PHP5

mail(to, subject, message [, headers] [, parameters])

to – $string

subject – $string

message – $string

headers – [optional] $string

parameters – [optional] $string

This uses the sendmail binary which may not be configured or available

depending on your system/setup. This is included here for basic reference. The

configuration and security concerns are outside of the scope of this book.

Security consideration:

http://www.securephpwiki.com/index.php/Email_Injection

Example:

$to = 'johndoe@example.com';

$subject = 'Hello';

$message = 'Hi John Doe';

$headers = 'From: janedoe@example.com' . "\r\n" .

'Reply-To: janedoe@example.com' . "\r\n" .

'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

exec(command [, output] [, return])

command – $string to execute the external program

output – [optional] Variable name to assign all the output of the command as

an array

return – [optional] Variable name to assign the return status as an $integer.

Works only when output is also present.

The function will return the last line of the executed program's output. If the

program fails to run and both output and return are both present, return will

be most commonly set to 0 when successfully executed and 127 when the

command fails.

Example (Linux specific program):

$lastline = exec('cal', $output, $return);

echo '<pre>'; // For better formatting of print_r()

print_r($output);

var_dump($lastline, $return);

Array

(

[0] => March 2008

[1] => Su Mo Tu We Th Fr Sa

[2] => 1

[3] => 2 3 4 5 6 7 8

17

Page 18 of 163

Mario Lurig

[4] => 9 10 11 12 13 14 15

[5] => 16 17 18 19 20 21 22

[6] => 23 24 25 26 27 28 29

[7] => 30 31

)

string(5) "30 31"

int(0)

header($string [, replace_flag] [, http_response_code])

replace_flag – [optional] $boolean default: TRUE, replace similar header

http_response_code – [optional] $integer

Sends an HTTP header specified as $string.

Note: Header() must be used prior to any other output is sent to the user/browser.

Use ob_start() to workaround this.

Examples:

header('Location: http://www.someotherplace.com');

// Redirects the user to the provided URL

header('HTTP/1.0 404 Not Found');

// Sends the HTTP status code 404

See Also:

ob_start() – Start the output buffer

Classes & Object Oriented PHP

While this is outside of the scope of this book, I have included a few notes

here on basic usage to extend the flexibility of this book.

Class Structure: ( brackets[] delineate optional syntax )

class class_name [extends base_class]{

var variable_name; // Defines a variable

function function_name([arguments]) {

// Stuff to do goes here

}

}

Refer to the containing class – use the reserved variable $this

Declare a class: $variable = new class_name();

Creating an object: $variable->function_name();

Static call to an object: class_name::function_name();

18

Page 24 of 163

Mario Lurig

24

Page 26 of 163

Mario Lurig

Switch

switch (expr) {

case value:

// Do this if value matches

break;

case value2:

// Do this if value2 matches

break;

default: // [optional]

// Do this if no other cases match. Does not have to be at the end

break;

}

expr – A $string, $integer, or $float to be compared against

A switch evaluates the expr against any number of cases or options, specifying

the behavior for each case.

Cases can be 'stacked' to allow the same portion of code to be evaluated for

different cases:

switch (expr) {

case value:

case value2:

// Do this if value or value2 matches

}

The switch is evaluated line-by-line, and therefore if there was no break

command, the case declaration would effectively be ignored and the code

would continue to be processed until the switch ends or a break; is reached.

$x = 1;

switch ($x) {

case 1:

echo '1'; // Note the lack of a break;

case 2:

echo '2'; // Without the break, this is processed line-by-line

}

12

Finally, the default statement is optional, but defines what to do if no cases

are matched. It can be used in troubleshooting to identify when you failed to

include a case for an expected output.

26

Alternative syntax for an if statement:

if (expr):

// If expr is TRUE, do this, then exit the IF loop

elseif (expr2):

// If expr is FALSE, and expr2 is TRUE, do this, then exit the

loop

else:

// If all expr's are FALSE, do this, then exit

endif;

Page 31 of 163

PHP Reference: Beginner to Intermediate PHP5

continue [$integer]

$integer – [optional] Specifies the number of nested loops to skip out of

Note: The $integer does not supply the number of iterations to skip, it always only

stops the current iteration from continuing any further.

Skips the rest of the current loop iteration and if applicable, continues to the

next iteration of the loop3

.

Example:

for ($x=1;$x<=10;$x++){

if ($x == 5){

continue;

} // The echo never occurs if $x == 5

echo $x;

}

1234678910

return [$variable]

$variable – [optional] The variable to be returned from a function

If used as part of a regular script and not part of a function, it works the

same as exit() or die(). Return is more commonly used as part of a function

to assign a value to the results of a function back at the original function call.

See Also:

Functions – Provides an example of returning a $variable as part of a

function

exit() – Terminate the current script immediately

include(file)

file - $string

Include and evaluate the file as part of the current script/page. This is an easy

way to store common variables, functions4

, or lines of HTML that will be

included by multiple scripts/pages. Failure of the function generates an error.

Example:

include('somefile.inc');

3 In the case of a switch, continue has the same effect as break

4 Functions should only be included once. Consider using include_once() or require_once()

31

Page 33 of 163

PHP Reference: Beginner to Intermediate PHP5

Global Variables

While some global variables can be created through the use of

define(), some are reserved because of a special function, giving access to

different types of data. All global variables listed below are arrays that may

or may not contain data, depending on the current script and environment.

$_SERVER

$_SERVER['HTTP_USER_AGENT'] – Browser description from header

[HTTP_USER_AGENT] => Mozilla/5.0 (X11; U; Linux i686; en-US; rv:

1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12

$_SERVER['HTTP_REFERER'] – The page address that referred the user

[HTTP_REFERER] => http://www.example.com/index.htm

$_SERVER['REMOTE_ADDR'] – The client's IP address

[REMOTE_ADDR] => 127.0.0.1

$_SERVER['DOCUMENT_ROOT'] – System root location of current script

[DOCUMENT_ROOT] => /opt/lampp/htdocs

$_SERVER['SCRIPT_FILENAME'] – Absolute path of current script

[SCRIPT_FILENAME] => /opt/lampp/htdocs/test.php

$_SERVER['REQUEST_URI'] – The Universal Resource Identifier for the page

[REQUEST_URI] => /test.php?test=value

$_SERVER['SCRIPT_NAME'] – The current scripts path

[SCRIPT_NAME] => /test.php

$_SERVER['QUERY_STRING'] – The current scripts path

[QUERY_STRING] => test=value

$_SERVER['PHP_SELF'] – The name of the current script, relative to the root

[PHP_SELF] => /test.php

♣ ♣ ♣

33

When submitting a form to the same page/file that contains it, you can use

the $_SERVER['PHP_SELF'] variable to dynamically provide the location.

<form method="POST" action="<?php echo $SERVER['PHP_SELF']; ?>">

<form method="POST" action="filename.php">

Page 37 of 163

PHP Reference: Beginner to Intermediate PHP5

Example:

$array = array();

$array2 = array( 'one', 'two', 'three' );

var_dump( is_array($array), is_array($array2) );

bool(true) bool(true)

is_int($variable)

Also known as: is_integer()

Determine whether the $variable is an integer. Returns TRUE if it is an

integer.

Example:

$int = 0;

$string = '0';

var_dump( is_int($int), is_int($string) );

bool(true) bool(false)

is_string($variable)

Determine whether the $variable is a string. Returns TRUE if it is a string.

Example:

$int = 0;

$string = '0';

var_dump( is_string($int), is_string($string) );

bool(false) bool(true)

is_numeric($variable)

Determine whether the $variable is an integer or a numeric string (e.g. "12").

If either is true, it will return TRUE.

Example:

$int = 10;

$string = '10';

var_dump( is_numeric($int), is_numeric($string) );

bool(true) bool(true)

See Also:

is_int() – Determine if a variable is an integer

is_string() – Determine if a variable is an string

37

Page 44 of 163

Mario Lurig

count_chars($string [, mode])

mode – [optional] $integer (0, 1, 2, 3, or 4) default: 0

Values: 0 – Returns an array with the count for all characters

1 – Returns an array with the count for all characters with at least

one instance in $string

2 – Returns an array with the count for all characters with zero

instances

3 – Returns a string of all characters contained within $string

4 – Returns a string of all characters not contained within $string

Checks $string for instances of all ASCII characters and counts the number of

times that a character is included within the string. Output varies depending

on mode.

Note: The key in the array is the ASCII byte-value of the character (modes 0-2)

while the string output is the characters themselves (modes 3 and 4).

Examples:

$string = 'Hello';

$array = count_chars($string, 1);

echo '<pre>'; // Not required, included for easier readability

print_r($array);

Array

(

[72] => 1

[101] => 1

[108] => 2

[111] => 1

)

foreach ($array as $key => $value){

$char = chr($key); // Character represented by the byte-value

$chararray[$char] = $value; // Make new array with characters

}

print_r($chararray);

Array

(

[H] => 1

[e] => 1

[l] => 2

[o] => 1

)

$usedcharacters = count_chars($string, 3);

var_dump($usedcharacters);

string(4) "Helo"

See Also:

chr() – Get the ASCII character represented by its byte-value

44

Page 45 of 163

PHP Reference: Beginner to Intermediate PHP5

chr($integer)

$integer – 0 - 255

Returns the single character string representation of the ASCII byte-value

($integer)

Example:

echo chr(72);

H

echo argument [, ...argument...]

Accepts multiple arguments separated by a comma

argument – A $scalar or function with scalar output7

Outputs the value of the argument to the user.

Example:

echo 'Hello';

Hello

print argument

argument – A $scalar or function with scalar output7

Outputs the value of the argument to the user, always returns 1. Use echo()

instead.

Example:

$x = print 'Hello';

print $x;

Hello

explode(delimiter, $string [, limit])

delimiter – $string, if set to '', explode will return FALSE

limit – [optional] $integer, default: no limit

Returns an array of strings created by searching through $string and

separating it by using the provided delimiter as the separation point. Limit

sets the maximum number of elements, with the last element of the array

being the remainder of the string8

.

7 $boolean is represented by 1 (TRUE) or nothing (FALSE) while floats may be displayed as

integers at greater than e6

8 If limit is negative, all values are returned except the last limit number of them

45

Page 48 of 163

Mario Lurig

• c - the input should be an integer between 0-255, representing

the ASCII byte-value. The character represented is output.

• d – the input should be an integer.

• e – the input is scientific notation.

• u – the input is an unsigned decimal number.

• f – the input is a float (locale aware).

• F - the input is a float (not locale aware).

• o – the input is an integer, an octal number is the output.

• s – the input is a string.

• x - the input is an integer, a hexadecimal number is the output

(with lowercase letters).

• X - the input is an integer, a hexadecimal number is the output

(with uppercase letters).

Examples:

Basic substitution, no optional specifiers

$string = 'cat';

$integer = 10;

echo sprintf("I have %d %s(s)", $integer, $string);

I have 10 cat(s)

Basic substitution, type specification automatic adjustments

$string = 'cat';

$string2 = '10 blah';

echo sprintf("I have %d %s(s)", $string2, $string);

I have 10 cat(s)

Using the sign specifier

$string = 'cat';

$integer = '10';

echo sprintf("Dagger has a %+d against %ss", $integer, $string);

Dagger has a +10 against cats

Using padding and width specifiers (default padding specifier of a space)

$string = 'cat'; // length, 3 characters

echo '<pre>'; // HTML Required to display the formating properly

echo sprintf("3 spaces added: |%6s", $string);

// Used padding of 6 characters, 6 – 3 = 3 spaces padded

Pad from line 3 spaces: | cat

Using padding and width using a zero ( 0 ) for padding

$month = 12;

$day = 1;

$year = 1980;

echo sprintf (" Date: %02d/%02d/%04d.", $month, $day, $year);

$year = 80;

echo sprintf (" Date: %02d/%02d/%04d.", $month, $day, $year);

Date: 12/01/1980. Date: 12/01/0080.

48

Page 59 of 163

PHP Reference: Beginner to Intermediate PHP5

$findarray = array('l', 'o');

$replace = 'x';

$string = "Hello";

$newstring = str_replace($findarray, $replace, $string);

echo $newstring;

Hexxx

See Also:

str_ireplace() – Case-insensitive version of str_replace()

strtr() – Simplified variation that also does not repeat on find/replace

str_ireplace(find, replace, subject [, count])

find – $string or $array

replace – $string or $array

subject – $string or $array

count – [optional] variable name - $integer

Replaces all instances of find with replace within subject. If subject is an array,

the find and replace occurs on all entries within the array.

If find and replace are arrays, the entire string is processed for each entry in

the arrays, finding the first entry in find and replacing it with the first entry

in replace, then repeating with the next set of entries. If there are more values

in the find array than the replace array, an empty string ('') is used as the

replacement. If find is an array and replace is a string, replace is used for every

entry in find.

The optional count variable will be set with the total number of replacements

that occurred.

Note: This function is case-insensitive.

Example:

$newstring = str_ireplace('find', 'replace', 'I will FIND');

echo $newstring;

I will replace

See str_replace() for more examples

See Also:

str_replace() – Case-sensitive version of str_ireplace()

59

Page 61 of 163

PHP Reference: Beginner to Intermediate PHP5

substr_replace(subject, replace, start [, length])

subject – $string or $array

replace – $string

start – $integer, if negative, counts from the end of the string

length – [optional] $integer default: strlen($string)

Replaces text till the end of the string within subject with replace starting after

character number start. If length is specified, only length number of characters

after start are replaced with replace when length is positive. If length is

negative, it represents the number of characters to stop replacing from the

end of the string.

If subject is an array, the function returns an array instead of a string, with

the replacement processed on every entry in the array.

Examples:

$string = substr_replace('1234567890', 'hello', 3);

echo $string;

123hello

echo substr_replace('1234567890', 'hello', 3, 2);

123hello67890

$array = array('1234567890', '0987654321');

$array = substr_replace($array, 'hello', -3, -2);

print_r($array);

Array ( [0] => 1234567hello90 [1] => 0987654hello21 )

See Also:

str_replace() – A find and replace of specific strings or array contents

substr_count(haystack, needle [, start] [, length])

haystack – $string

needle – $string

start – [optional] $integer, must be 0 or a positive number

length – [optional] $integer, must be 0 or a positive number

Returns the total number of instances of needle in haystack. If start is provided,

it ignores start number of characters from the beginning. If length is provided,

it only checks length characters from start.

Examples:

echo substr_count('abcdef', 'bc');

1

echo substr_count('abcdef', 'bc', 3);

0

61

Page 62 of 163

Mario Lurig

str_pad($string, pad_length [, pad_string] [, type])

pad_length – $integer, must be positive and greater than strlen($string)

pad_string – [optional] $string default: space (' ')

type – [optional] $integer (0, 1, or 2) default: 0 (pad right side only)

Other values: 1 (pad left side only)

2 (pad both sides)12

Inserts into $string spaces or the optional pad_string till $string is pad_length

number of characters long.

Examples:

$string = 'Hello';

echo '<pre>'; // So preformatted text is shown

echo str_pad($string, 7), '|';

Hello |

$string = 'Hello';

echo str_pad($string, 10, '#', 2);

##Hello###

See Also:

sprintf() – More complex function designed for formatting strings

str_repeat($string, multiplier)

multiplier – $integer

Returns a string with $string repeated multiplier times.

Example:

echo str_repeat('123', 3);

123123123

str_shuffle($string)

Randomly shuffles the characters in a string. A string jumble, essentially.

Example:

echo str_shuffle('Hello World!');

HreW! ollodl

12 Padding characters are alternated one-by-one, right side then left side

62

Page 63 of 163

PHP Reference: Beginner to Intermediate PHP5

str_split($string [, length])

length – [optional] $integer

Returns an array of $string separated by each character or the optional length

number of characters.

Examples:

$array = str_split('Hello');

print_r($array);

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )

$array = str_split('Hello', 2);

print_r($array);

Array ( [0] => He [1] => ll [2] => o )

See Also:

chunk_split() – Splits a string after a specific length with \r\n and returns a

string

str_word_count($string [, option] [, characters])

option – [optional] $integer (0, 1, or 2) default: 0 (returns: number of words)

Other values: 1 (returns: array containing all words found)

2 (returns: array with position => word)

characters – [optional] $string

Counts the number of words inside $string and returns that count by default

(can be altered by options). If characters is present, it contains any characters

that should be considered the same as a letter.

Examples:

$string = 'Welcome to the jungle';

echo str_word_count($string);

4

$string = 'Welcome to the jun3gle';

$without = str_word_count($string, 0);

$withchar = str_word_count($string, 0, '3');

echo "Without: $without, WithChar: $withchar";

Without: 5, WithChar: 4

$string = 'Welcome to the jungle';

echo '<pre>'; // For easier readability

$array = str_word_count($string, 1);

print_r($array);

Array

(

[0] => Welcome

[1] => to

[2] => the

63

Page 64 of 163

Mario Lurig

[3] => jungle

)

$array = str_word_count($string, 2);

print_r($array);

Array

(

[0] => Welcome

[8] => to

[11] => the

[15] => jungle

)

strip_tags($string [, allowed_tags])

allowed_tags – [optional] $string

Remove HTML tags and comments from $string. If specific tags should be

excluded, they can be specified inside allowed_tags.

Examples:

$string = "<p>This is a paragraph. </p><strong>Yay!</strong>";

echo strip_tags($string), strip_tags($string, '<p>');

HTML Source Code:

This is a paragraph. Yay!

echo strip_tags($string, '<p>');

<p>This is a paragraph. </p>Yay!

See Also:

htmlspecialchars() – Convert HTML special characters to their entity

equivalent

strpos(haystack, needle [, start])

haystack – $string

needle – $string

start – [optional] $integer

Returns the position (number of characters from the beginning of haystack) of

the first occurrence of needle in haystack. If start is included, searching begins

after start number of characters.

Note: If needle is not found in haystack, FALSE is returned. See tip below.

Example:

$string = 'And now for something completely different';

$needle = 'thing';

echo strpos($string, $needle);

16

64

Page 65 of 163

PHP Reference: Beginner to Intermediate PHP5

See Also:

strrpos() – Finds the last occurrence of needle in haystack

stripos() – Finds the first occurrence of needle in haystack, case insensitive

♣ ♣ ♣

strrpos(haystack, needle [, start])

haystack – $string

needle – $string

start – [optional] $integer

Returns the position (number of characters from the beginning of haystack) of

the last occurrence of needle in haystack. If start is included and is a positive

integer, searching begins after start number of characters; if negative, it stops

searching start number of characters from the end of the string.

Note: If needle is not found in haystack, FALSE is returned. See strpos() for tip.

Example:

$string = 'hello';

$needle = 'l';

echo strpos($string, $needle); // Search for first occurrence

echo '<br />'; // XHTML line break

echo strrpos($string, $needle); // Search for last occurrence

2

3

65

Note the following difference in evaluating the output of this function:

$string = 'hello';

$needle = 'h';

if (strpos($string,$needle) == FALSE){ // evaluating equality

echo 'Not Found!';

}

Not Found!

Because strpos($string,$needle) equaled 0, and the boolean FALSE

evaluates equal to the integer 0, the expression is true and the echo occurs.

Therefore, it is important to evaluate the expression for an identical match

( === ).

$string = 'hello';

$needle = 'h';

if (strpos($string,$needle) === FALSE){ // identical evaluation

echo 'Not Found!';

}else{

echo 'Found!';

}

Found!

Page 66 of 163

Mario Lurig

See Also:

strpos() – Finds the first occurrence of needle in haystack

strripos() – Finds the last occurrence of needle in haystack, case insensitive

stripos(haystack, needle [, start])

haystack – $string

needle – $string

start – [optional] $integer

Returns the position (number of characters from the beginning of haystack) of

the first occurrence of needle in haystack, case insensitive. If start is included,

searching begins after start number of characters.

Note: If needle is not found in haystack, FALSE is returned. See strpos() for tip.

Example:

$string = 'And now for something completely different';

$needle = 'NOW';

echo stripos($string, $needle);

4

See Also:

strripos() – Finds the last occurrence of needle in haystack, case insensitive

strpos() – Finds the first occurrence of needle in haystack, case sensitive

strripos(haystack, needle [, start])

haystack – $string

needle – $string

start – [optional] $integer

Returns the position (number of characters from the beginning of haystack) of

the last occurrence of needle in haystack, case insensitive. If start is included

and is a positive integer, searching begins after start number of characters; if

negative, it stops searching start number of characters from the end of the

string.

Note: If needle is not found in haystack, FALSE is returned. See strpos() for tip.

Example:

$string = 'hello';

$needle = 'L';

echo strrpos($string, $needle); // Search for last occurrence

3

66

Page 67 of 163

PHP Reference: Beginner to Intermediate PHP5

See Also:

strrpos() – Finds the last occurrence of needle in haystack, case sensitive

stripos() – Finds the first occurrence of needle in haystack, case insensitive

strstr(haystack, needle)

haystack – $string

needle – $string

Find if needle is found in haystack and returns the first occurrence of needle to

the end of haystack.

Note: If needle is not found in haystack, FALSE is returned.

Example:

$string = 'www.example.com';

$needle = 'example';

echo strstr($string, $needle);

example.com

See Also:

stristr() – case insensitive version of strstr()

stristr(haystack, needle)

haystack – $string

needle – $string

Finds if needle is found in haystack and returns the first occurrence of needle to

the end of haystack, case insensitive.

Note: If needle is not found in haystack, FALSE is returned.

Example:

$string = 'www.example.com';

$needle = 'EXAMPLE';

echo stristr($string, $needle);

example.com

See Also:

strstr() – case sensitive version of stristr()

strlen($string)

The length of $string, or 0 if it is empty.

67

Page 68 of 163

Mario Lurig

Example:

$string = 'Hello!';

echo strlen($string);

6

strtolower($string)

Converts all characters in $string to lowercase and returns the new string.

Example:

$string = 'Mario Lurig';

echo strtolower($string);

mario lurig

strtoupper($string)

Converts all characters in $string to uppercase and returns the new string.

Example:

$string = 'Mario Lurig';

echo strtoupper($string);

MARIO LURIG

ucfirst($string)

Converts the first character in $string to uppercase and returns the new

string.

Example:

$string = 'i wish i had some capitalization';

echo ucfirst($string);

I wish i had some capitalization

ucwords($string)

Converts the first alphabetic characters of words in $string to uppercase and

returns the new string.

Example:

$string = 'i wish i had 3three some capitalization';

echo ucwords($string);

I Wish I Had 3three Some Capitalization

68

Page 69 of 163

PHP Reference: Beginner to Intermediate PHP5

strpbrk(haystack, characters)

haystack – $string

characters – $string

Find if any of the characters in needle are found in haystack and returns the

first occurrence of the character found in needle to the end of haystack.

Note: If needle is not found in haystack, FALSE is returned.

Example:

$string = 'www.example.com/index.htm';

$needle = './c';

echo strpbrk($string, $needle); // Finds the period (.) first

.example.com/index.htm

See Also:

strstr() – Same as strpbrk() but searches for a string instead of characters

strrev($string)

Reverses a string.

Example:

echo strrev('hello world');

dlrow olleh

69

Page 70 of 163

Mario Lurig

70

Page 71 of 163

PHP Reference: Beginner to Intermediate PHP5

Array Functions

It took me a while to learn about arrays, they were these scary things

with keys and values, associative and indexed, and then you could have an

array inside an array... I was scared. Truth was, they were infinitely useful in

keeping things organized, efficient, and quick. Without foreach, code would

be bloated 2-3 times what it could be. So don't be scared, and learn to love

arrays.

One quick note: For easier readability, the output in this section is

surrounded by the HTML <pre> (preformatted) tag for easier readability if

an array contains more than one entry. Unlike all other chapters where it is

included in the supplied code, it is not in this chapter as a space

consideration.

Array Nomenclature

Common usage and syntax for arrays.

Example:

$array = array(); // Define $array as... an array

$array = array( 'value', 'two', 'three' ); // Indexed array

$array = array( 'key' => 'value', 'job' => 'slacker' ); // Associative

$array = array();

$array[] = 'value'; // Assign value to next available indexed key

$array[0] = 'value'; // Assign value to the key of 0

$array['name'] = 'value'; // Assign value to the key name

// Assign the value of key 0 in $array to $value

$value = $array[0];

// Assign the value of the key name in $array to $value

$value = $array['name'];

71

Page 72 of 163

Mario Lurig

array_change_key_case($array [, option])

option – [optional] $integer (0 or 1) default: 0 (lowercase)

Other value: 1 (uppercase)

Changes the case of the keys inside of $array to lowercase (default) or

uppercase.

Examples:

$array = array( 'NaMe' => 'BoB' );

print_r( array_change_key_case($array) );

Array ( [name] => BoB )

print_r( array_change_key_case($array, 1) );

Array ( [NAME] => BoB )

array_chunk($array, size [, preserve_keys])

size – $integer

preserve_keys – [optional] $boolean default: FALSE, array is reindexed

numerically

Splits the $array by the size number of values for each new array, returning a

multi-dimensional indexed array. If preserve_keys is not specified, the values

are reindexed in an indexed array. If preserve_keys is set to TRUE, keys are

retained.

Example:

$array = array( 'name' => 'bob', 'job' => 'dad' );

$newarray = array_chunk($array, 1);

print_r($newarray);

Array

(

[0] => Array

(

[0] => bob

)

[1] => Array

(

[0] => dad

)

)

$array = array( 'name' => 'bob', 'job' => 'dad' );

$newarray = array_chunk($array, 1, TRUE);

print_r($newarray);

Array

(

[0] => Array

(

[name] => bob

)

72

Page 73 of 163

PHP Reference: Beginner to Intermediate PHP5

[1] => Array

(

[job] => dad

)

)

array_combine(key_array, value_array)

key_array – $array

value_array – $array

Creates a new array using the values from key_array as the keys and the

values from value_array as the values.

Note: Returns FALSE if number of entries in both arrays does not match.

Example:

$keys = array ( 'name', 'job', 'age' );

$values = array ( 'Bob', 'knight', 42 );

$newarray = array_combine($keys, $values);

print_r($newarray);

Array

(

[name] => Bob

[job] => knight

[age] => 42

)

See Also:

array_merge() – Combine the keys and values of multiple arrays

array_merge($array [, ...$array...])

Can accept multiple array values, and behaves differently with only one argument

If supplied with only one indexed $array, it reindexes that array

continuously.

If supplied with more than one $array, the content of both arrays are

combined with all indexed keys included in the new array, while associative

keys that are identical take the value of the last $array supplied.

Example:

$array = array ( 3 => 'one', 0 => 'two', 2 => 'three' );

print_r( array_merge($array) );

Array

(

[0] => one

[1] => two

[2] => three

)

73

Page 74 of 163

Mario Lurig

$array = array ( 'zero', 'one', 'name' => 'Bob' );

$array2 = array ( 'alsozero', 'name' => 'John', 'job' => 'farmer' );

print_r( array_merge($array, $array2) );

Array

(

[0] => zero

[1] => one

[name] => John

[2] => alsozero

[job] => farmer

)

See Also:

array_combine() – Combine the values of two arrays into a key=>value array

♣ ♣ ♣

array_count_values($array)

Returns an array with the unique values in $array as the keys and their count

as the values.

Note: Does not work for multi-dimensional arrays.

Example:

$array = array ( 'zero', 'one', 'zero' );

print_r( array_count_values($array) );

Array

(

[zero] => 2

[one] => 1

)

See Also:

count() – Count the total number of entries in an array

74

If you want to combine two arrays and do not mind if values with the same

keys accept the values from the first array and discard any other arrays

supplied, simply use the plus sign ( + ).

$array = array ( 'zero', 'name' => 'Bob', 'job' => 'player' );

$array2 = array ( 'alsozero', 'job' => 'farmer' );

print_r( $array + $array2 );

Array

(

[0] => zero

[name] => Bob

[job] => player

)

Page 75 of 163

PHP Reference: Beginner to Intermediate PHP5

count($array [, mode])

mode – [optional] $integer default: 0, does not count multidimensional arrays

Other value: 1, counts entries within multidimensional arrays

Counts the number of elements in $array. By default, entries within arrays

that are part of $array (multidimensional arrays) are not counted unless mode

is set to 1.

Examples:

$array = array ('zero',

'names' => array ( 'john', 'dave' ),

'ages' => array ( 22, 34 ) );

echo count($array);

3

echo count($array, 1);

7

See Also:

array_count_values() – Get the number of unique values inside of an array

array_diff(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

Compares the values of all $array(s) against the values in first_array and

returns an array with the entries of first_array which do not share values with

entries in $array(s).

Example:

$array = array( 'one', 'two', 'three', 'four' );

$array2 = array( 'two', 'three' );

$array3 = array( 'bob' => 'one' );

// value is 'one', matching $array

print_r( array_diff($array, $array2, $array3) );

Array ( [3] => four )

See Also:

array_diff_key() – Same comparison, but based on keys instead of values

array_diff_assoc() – Same comparison, but based on both keys and values

array_intersect() – Similar, but returns entries that are present in all $array(s)

75

Page 76 of 163

Mario Lurig

array_diff_key(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

Compares the keys of all $array(s) against the keys in first_array and returns

an array with the entries of first_array which do not share keys with entries in

$array(s).

Example:

$array = array( 'zero', 'name' => 'john', 'job' => 'john' );

$array2 = array( 'alsozero', 'job' => 'john' );

print_r( array_diff_key($array, $array2));

Array ( [name] => john )

See Also:

array_diff() – Same comparison, but based on values only

array_diff_assoc() – Same comparison, but based on both keys and values

array_diff_assoc(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

Compares the contents of all $array(s) against the keys and values in

first_array and returns an array with the entries of first_array which do not

share exact keys and values with entries in $array(s).

Example:

$array = array( 'zero', 'one', 'name' => 'john' );

$array2 = array( 'zero', 'alsoone', 'name' => 'john' );

print_r( array_diff_assoc($array, $array2) );

Array ( [1] => one )

See Also:

array_diff_key() – Same comparison, but based on keys instead of values

array_diff() – Same comparison, but based on values only

array_intersect(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

Compares the values of all $array(s) against the values in first_array and

returns an array with the entries of first_array which share values with

entries from all $array(s).

76

Page 77 of 163

PHP Reference: Beginner to Intermediate PHP5

Example:

$array = array( 'one', 'two');

$array2 = array( 'two', 'one', 'three', 'four' ); // 'one','two' match

$array3 = array( 'bob' => 'one' );

// only 'one' matches

print_r( array_intersect($array, $array2, $array3) );

Array ( [0] => one )

See Also:

array_intersect_key() – Same comparison, but based on keys

array_intersect_assoc() – Same comparison, but based on both keys and

values

array_diff() – Similar, but returns entries that are not present in $array(s)

array_intersect_key(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

Compares the keys of all $array(s) against the keys in first_array and returns

an array with the entries of first_array which share keys with entries from all

$array(s).

Example:

$array = array( 'zero', 'name' => 'john', 'job' => 'john' );

$array2 = array( 'alsozero', 'job' => 'john' );

print_r( array_intersect_key($array, $array2));

Array

(

[0] => zero

[job] => john

)

See Also:

array_intersect() – Same comparison, but based on values only

array_intersect_assoc() – Same comparison, but based on both keys and

values

array_intersect_assoc(first_array, $array [, ...$array...])

Accepts multiple $array for comparison against first_array

first_array – $array

77