Php for Files

Embed Size (px)

Citation preview

  • 8/12/2019 Php for Files

    1/176

    PHP Reference: Beginner to Intermediate PHP5

    PHP Reference: Beginner toIntermediate PHP5

    Mario Lurig

    1

  • 8/12/2019 Php for Files

    2/176

    PHP Reference: Beginner to Intermediate PHP5

    PHP Reference:

    Beginner to Intermediate PHP5

    ISBN: 978-1-4357-1590-5

    Creative Commons Attribution-NonCommercial-SareAli!e "#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 orlicensor (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 theresulting 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 thiswork.

    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 wit !ermi""ion:

    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

    http://www.flickr.com/lwr/http://www.flickr.com/lwr/http://www.labworks.eu/http://www.labworks.eu/http://www.flickr.com/evaekeblad/http://www.flickr.com/duncan/http://www.flickr.com/duncan/http://www.flickr.com/lwr/http://www.labworks.eu/http://www.flickr.com/evaekeblad/http://www.flickr.com/duncan/
  • 8/12/2019 Php for Files

    3/176

    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

  • 8/12/2019 Php for Files

    4/176

    Mario Lurig

    4

  • 8/12/2019 Php for Files

    5/176

    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 thePHP.netmanual (

    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 thewhatof 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 wasborn.

    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 includingis_int()and notis_long().

    5

    http://php.net/http://www.php.net/manual/en/http://www.php.net/manual/en/http://php.net/http://www.php.net/manual/en/
  • 8/12/2019 Php for Files

    6/176

    PHP Reference: Beginner to Intermediate PHP5

    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), includingboolean

    $variable - A string, integer, float, arrayorboolean1

    $scalar - Astring, integer, float,orboolean

    $string - Astringvariable or its equivalent (e.g."string" or 'string' ) $array - Anarray

    variable or its equivalent (e.g.array( 'one' , 'two' , 'three' ) )key- Represents the key

    (integerorstring)of anarray(e.g.$array[key] )value- In relation to anarray,

    represents the$variablevalue (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 'Goodye World!';

    }

    // lternati"e syntax if

    ($x == 1) #echo 'Hello World!';

    else#

    echo 'Goodye 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. Thedefinitionandexamplesection is separated from the

    extraneoustipsection 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 usuall% use& 'itin an e()ression# *ile it is also evaluate& as a variable+ out)utresults ma% var% an& are note& 'itin s)eci,ic ,unctions 'enever )ossible

  • 8/12/2019 Php for Files

    7/176

    PHP Reference: Beginner to Intermediate PHP5

    function name(input, [optional input])

    Description/definition

    Example:

    ode %ith // co&&ents

    tt of code as seen thro*h a %e ro%ser's ott

    See Also:

    function -simplified and relevant definition

    function -simplified and relevant definition

    . . .

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

    +xtra code related tothe ti

    tt

    ,-. = f

    ,1. = ode}

    Thanks, and enjoy the show!

    7

  • 8/12/2019 Php for Files

    8/176

    Mario Lurig

    8

  • 8/12/2019 Php for Files

    9/176

    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 CodeFor portability and compatibility, always use the long form. Long

    form:0h exr

    Short form:0 expr

    Short form equivalent of Note:

    No closing semicolon (;) is required.0= exr

    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:

    $strin* = 'Sin*le 2otes';

    echo '$strin* ' ;

    $strin*

    9

  • 8/12/2019 Php for Files

    10/176

    PHP Reference: Beginner to Intermediate PHP5

    " " (double quotes) - Variables inside double quotes are evaluated for their values.

    Example:

    $strin* = '3ole 2otes';

    echo 4$strin*4;

    3ole 2otes

    Backslash (Escape Character)

    Escapes characters that should be evaluated literally when inside double

    quotations.

    Example:

    $strin* = '3ole 2otes';

    echo 45$strin* is set as $strin*4;

    $strin* is set as 3ole 2otes

    Special Characters

    backslash ( \ )

    question mark ( ? )

    single ( ' ) quotes

    double ( " ) quotes

    dollar sign ( $ )

    Example:

    $strin* = 'Hello World!';

    echo 46he "ariale 5$strin* contains 5' $strin* 5' 54 554; 6he "ariale

    $strin* contains 5' Hello World! 5' 4 5 echo '6he "ariale 5$strin*

    contains 5' $strin* 5' 54 55'; 6he "ariale 5$strin* contains ' $strin*

    ' 54 5

    Comments

    Single line, for everything to the right of the doubleforwardslashes:// 6his is a co&&ent

    Multiple lines, opening and closing tags: /* *//7 6his is a

    co&&ent 7/

    10

  • 8/12/2019 Php for Files

    11/176

    PHP Reference: Beginner to Intermediate PHP5

    Formatting Characters

    5n - New line

    5r - Carriage return

    5t - Tab

    5 - Backspace

    define(name,value[, $boolean])

    name-$string

    value-$scalar

    $boolean- [optional]default:FALSE, case-sensitive

    Define a constant, a set value that is assigned globally, making it available to

    functions and classes without passing them directly as an argument.

    Examples:

    define('H+88'9 'Hello World!');echo H+88;

    Hello World!

    define('G:++6

  • 8/12/2019 Php for Files

    12/176

    PHP Reference: Beginner to Intermediate PHP5

    if (-==-){

    fnction hello(){ echo 'Hello ';

    }

    }hello();

    there();

    fnction there()

    { echo 'there';

    }

    Hello there

    Functions can have no arguments (as above), arguments passed to them, or default

    arguments with passed arguments as optional. The argument names are used

    within that function as variable names.

    fnction ar*s($a9 $){

    // Has no defalt "ales9 re>ires t%o ints echo 4a= $a9 = $4;

    }ar*s(19?); a =19 = ?

    Some examples using the following function:

    fnction ar*s($a = 19 $ = ?){ //

    Has defalt "ales set $c = $a @

    $;

    echo 4a = $a9 = $9 a@ = $c4;

    }

    ar*s();

    a = 19 = ?9 a@ = A

    ar*s (B9B);

    a = B9 = B9 a@ = 1-

    ar*s(1-);

    a = 1-9 = ?9 a@ = 1?

    ar*s($3oes

  • 8/12/2019 Php for Files

    13/176

    PHP Reference: Beginner to Intermediate PHP5

    If multiple pages will refer to the same functions, create a separate

    functions.phpfile (name it whatever you like) andrequire()or

    require_once()with pages that will need to use those functions. For speed

    and file size, page specific functions should be included directly on the

    necessary page.____________________________________________________________

    exit([$string])

    die([$string])

    Stops the current script and outputs the optional$string.

    Example:

    $reslt = C&ys>lDconnect('d'9 'ser'9 '%')or die('nale to connect to dataase!'); echo

    'f it fails9 this %ill ne"er e seen';

    nale to connect to dataase!

    Note:The above output would only display if it failed. If the @ was not present before

    mysql_connect(), PHP would output a warning as well.

    eval($string)

    Evaluates a string as if it was code. This can be used to store code in a database and

    have it processed dynamically by PHP as if it were part of the page. All appropriate

    aspects of code must be included, such as escaping items with a backslash (\) and

    including a semicolon (;) at the end of the string.

    Example:

    $na&e = 'Eario';

    $strin* = 'Ey na&e is $na&eF'; // otes echo

    $strin*;

    $code = 45$e"alstrin* = 54 $strin* 54 ;4;

    // +ffect of acslash escae# $code = 4$e"alstrin* = 4 $strin* 4 ;4;

    e"al($code); // e"al($e"alstrin* = 4 Ey na&e is $na&e 4 ;); // $e"alstrin* is

    the sa&e as $strin*9 excet %ith dole >otes no% echo $e"alstrin*;

    Ey na&e is $na&eF Ey na&e is EarioF

    sleep($integer)

    Pauses PHP for$integeramount of seconds before continuing.

    Example:

    slee(?); // ase for ? seconds

    13

  • 8/12/2019 Php for Files

    14/176

    PHP Reference: Beginner to Intermediate PHP5

    usleep($integer)

    Pauses PHP for$integeramount of microseconds before continuing.

    Example:

    slee(1------); // ase for 1 second

    uniqid([$scalar [,entropy]])

    entropy- [optional]$booleandefault:FALSE, 13 character output

    Generate a unique ID based on the$scalar.If no input is given, the current time in

    microseconds is used automatically. This is best used in combination with other

    functions to generate a more unique value. If the$scalaris an empty string ('') and

    entropyis set to TRUE, a 26 character output is provided instead of a 13 character

    output.

    Examples:

    $id = ni>id();

    echo $id;

    IccJ?cK1IcKK

    $rando&Did = ni>id(&tDrand());

    echo $rando&Did;

    LA KBI ?B K1 IccJ?cK1Icd

    $&dB = &dB($rando&Did);

    echo $&dB;

    eaBI Aadcdf? -?1BA K1J?c?dfA JB1f

    See Also:

    md5() -MD5 algorithm based encryption

    setcookie(name[,value][,time][,path][,domain][,secure][,httponly])

    name-$string

    value- [optional]$string

    time- [optional]$integerdefault:till the end of the sessionpath-

    [optional]$stringdefault:current directorydomain- [optional]

    $stringdefault:current domain(e.g.

    http ://www.example.com)secure- [optional]$booleandefault:FALSE,

    does not require a secure

    connection

    httponly- [optional]$booleandefault:FALSE, available to scripting languages

    14

    http://www.example/http://www.example/http://www.example/
  • 8/12/2019 Php for Files

    15/176

    PHP Reference: Beginner to Intermediate PHP5

    Sets a cookie2, visible to the server on the next page load. To send then default value,

    use a set of single quotes ('') for each argument you want to skip except thetime

    argument, which should use0to send thedefaultvalue. In most cases, providing the

    name, value, time,anddomainwill cover most uses (with '' for path).

    Examples:

    setcooie('ooie'9'Set till end of this session'9-);

    // 6his %ill dislay roerly after the a*e has een reloaded

    rintDr($DM+);

    rray ( ,ooie. = Set till end of this session )setcooie('ooie'9'Set for L- seconds for all sdo&ains of exa&leFco&9 sch

    as %%%F9 &ailF9 etcF'9ti&e()@L-99999Fexa&leFco&');

    rintDr($DM+);

    rray ( ,ooie. = Set for L- seconds for all sdo&ains of exa&leFco&9

    sch as %%%F9 &ailF9 etcF )

    Some common times used for expiration: time()

    +60*60*24 is equal to 1 day time()+60*60*24*30 is

    equal to 30 days

    time()-1 is one second in the past, used toexpire/deletea cookiesetcooie ( ' ooie ' '9ti&e()N1) ;

    // exires the ooie na&ed 'ooie'F

  • 8/12/2019 Php for Files

    16/176

    PHP Reference: Beginner to Intermediate PHP5

    et_magic_quotes_gpc()

    Returns0if it is off,1otherwise.

    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 (*etD&a*icD>otesD*c()){

    echo 'Ea*ic 2otes is on!'; }

    else{

    echo 'Ea*ic 2otes is

  • 8/12/2019 Php for Files

    17/176

    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 = 'RohndoeCexa&leFco&';

    $sRect = 'Hello'; $&essa*e =

    'Hi ohn 3oe';

    $headers = 'Pro RanedoeCexa&leFco&' F 45r5n4 F

    ':elyN6o# RanedoeCexa&leFco&' F 45r5n4 F

    'TNEailer# QHQ/' F h"ersion();

    &ail($to9 $sRect9 $&essa*e9 $headers);

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

    command-$stringto execute the external program

    output- [optional] Variable name to assign all the output of thecommandas an array

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

    only whenoutputis also present.

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

    fails to run and bothoutputandreturnare both present,returnwill be most commonly

    set to 0 when successfully executed and 127 when thecommandfails.

    Example (Linux specific program):

    $lastline = exec('cal'9 $ott9 $retrn);

    echo '0re'; // Por etter for&attin* of rintDr()

    rintDr($ott);

    "arDd&($lastline9 $retrn);

    rray ,-. = Earch ?--J,1. = S Eo 6 We 6h Pr Sa

    ,?. = 1,A. = ? A B L I J

    ,. = K 1- 11 1? 1A 1 1B,B. = 1L 1I 1J 1K ?- ?1 ??,L. = ?A ? ?B ?L ?I ?J ?K,I. = A- A1

    )strin*(B) 4A- A14int (-)

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

    replace_flag- [optional]$booleandefault: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('8ocation# htt#//%%%Fso&eotherlaceFco&'); //

    :edirects the ser to the ro"ided :8 header('H66Q/1F-

    http://www.securephpwiki.com/index.php/Email_Injectionmailto:'[email protected]'mailto:[email protected]'mailto:[email protected]'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2Fwww.someotherplace.com'http://www.securephpwiki.com/index.php/Email_Injectionmailto:'[email protected]'mailto:[email protected]'mailto:[email protected]'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2Fwww.someotherplace.com'
  • 8/12/2019 Php for Files

    18/176

    -

  • 8/12/2019 Php for Files

    19/176

    Operators

    When comparing or processing variables and other values you use

    operators. Without them, PHP would be more of a word jumble instead of a

    language. In some unique cases, operators slightly alter the relationship between two

    variables or their function within PHP. Without further adieu, here they are.

    Basic Operators

    Add ( + ):$a = 1; $a = $a @ B; // $a is e>al to L Subtract

    ( - ):$s = 1-; $s = $s N B; // $s is e>al to B Multiply ( * ):$&

    = ?; $& = $& 7 1-; // $& is e>al to ?-

    Divide ( / ):$d = ?-; $d = $d / B; // $d is e>al to Modulus (

    % ) Provides the remainder after division:$ = B; $ = $ O ?; // $ is e>al to 1

    Assignment Operators

    Add ( += ):$a = 1; $a @= B; // $a is e>al to L Subtract (

    -= ):$s = 1-; $s N= B; // $s is e>al to B Multiply ( *= ):

    $& = ?; $& 7= 1-; // $& is e>al to ?-

    Divide ( /= ):$d = ?-; $d /= B; // $d is e>al to

    Modulus ( %= ) Provides the remainder after division:$ = B; $ O= ?; // $ is e>al to 1

    Concatenate ( .= ) Join onto the end of a string:

    $c = B; $c F= ?; // $c is no% a strin*9 'B?'

    See Also:

    Concatenate -Join together in succession

  • 8/12/2019 Php for Files

    20/176

    Comparison Operators

  • 8/12/2019 Php for Files

    21/176

    PHP Reference: Beginner to Intermediate PHP5

    Greater Than ( > ):2 > 1

    Less Than ( < ):1 < 2

    Greater Than or Equal To ( >= ):2 >= 2

    Less Than or Equal To (

  • 8/12/2019 Php for Files

    22/176

    Mario Lurig

    Short-Hand Plus or Minus one

    Also known as:Increment (

    $integer++;) Decrement (

    $integer--;)

    Example:

    $a = 1;

    $a = $a @ 1; // $a is no% e>al to ? $a@@; // $a is no% e>al to A

    $aNN; // $a is no% e>al to ? a*ain9 sa&e as $a = $a N 1;

    @ - Suppress Errors

    Placing the commercial at symbol (@) before a function tells PHP to suppress any

    errors generated by that function.

    Examples:

    inclde('3oes

  • 8/12/2019 Php for Files

    23/176

    PHP Reference: Beginner to Intermediate PHP5.

    . .

    Use this for functions when you wish to simply alter the original variable and return

    it again to the same variable name with its new value assigned.

    fnction add(U$"ar){ // 6he U is efore the ar*&ent $"ar $"ar@@;

    }

    $a = 1;

    $ = 1-;

    add($a);

    echo 4a is $a94;

    add($);

    echo 4 a is $a9 and is $4; //

  • 8/12/2019 Php for Files

    24/176

    Mario Lurig

    Assignment ( = ): Assigns the value on the right to the variable on the left

    Equality ( == ): Checks if the left and right values are equal

    Identical ( === ): Checks if the left and right values are equal AND identical

    Example:

    $a = 1; // Sets the "ale of $a as 1 y assi*n&ent$ = 6:+; // Sets the "ale of $ to the oolean 6:+

    if ($a == $){

    echo 'a is e>al to F';

    }

    if ($a === $){

    echo 'a is identical and e>al to F';

    }

    a is e>al to F

    Not ( ! ), Not Equal to ( != ), Not Identical to ( !== )

    Used in conditional statements to evaluate as true a FALSE result of an

    expressionor if a value is NOT equal to the second value.

    Example:

    $a = 1;

    if (!isset($a)){ // f the "ariale $a is al Vero

    SeeThe Equal Signabove for equality versus identical

    Concatenate (The Period)

    A period is used to join dissimilar items as part of a string in the same order as they

    are listed. In many cases this is used to reference the value of a function or of an

    array, which cannot be referenced within double quotations ( "" ) when being

    assigned to a$stringvariable.

    Example:

    $array = array( 1 = 'Hello' );$strin* = 'World';echo '$strin* in sin*le >otes9 follo%ed y ' F $array,1. F 4$strin*4;

    $strin* in sin*le >otes9 follo%ed y HelloWorld

    "4

  • 8/12/2019 Php for Files

    25/176

    PHP Reference: Beginner to Intermediate PHP5

    Comparison Operators (non-arithmetic)

    and ( && )

    or( II )

    xor ( xor ) - Or, but not All

    Examples:

    if (1 == 1 UU ? == ?){ echo 'nd is6re';

    }

    nd is 6re

    if (1 == 1 ? == ?){echo 't least one of these is 6re';

    }

    t least one of these is 6re

    if (1 == 1 xor ? == 1-){echo 'ne of these is 6re9 t not oth';

    }

    ne of these is 6re9 t not oth

    "5

  • 8/12/2019 Php for Files

    26/176

    Mario Lurig

    "$

  • 8/12/2019 Php for Files

    27/176

    PHP Reference: Beginner to Intermediate PHP5

    Control Structures

    The heart of PHP is the control structures. Variables and arrays are lonely

    without them as they facilitate comparisons, loops, and large hands telling you to go

    that way and do it this way. Okay, I made that last part up. Here we go!

    If, Elself, Else

    if (expr) {

    // f expr is 6:+9 do this9 then exit the P loo }

    elseif (expr!) {// f expr is P8S+9 and expr! is 6:+9 do this9 then exit the loo }

    else{

    // f all expr"s are P8S+9 do this9 then exit

    }

    There can be only one instance ofelsein anifstatement, but multipleelseifexpressions

    are allowed prior to theelsestatement.

    Example:

    $x = 1;

    if ($x 0 1) {

    echo '$x is less than 1'; }elseif ($x == 1){ // als9

    for co&arison

    echo '$x is e>al to 1'; }

    else{

    echo '$x is neither e>al to 1 or less than 1';}

    $x is e>al to 1

    See Also:

    switch -A simpler, more organized usage than multiple if/elself

    combinations

    break -Stops a loop and exits regardless of if the statement evaluates as true

    . . .

    "7

  • 8/12/2019 Php for Files

    28/176

    PHP Reference: Beginner to Intermediate PHP5

    Alternative syntax for anifstatement:

    i f (expr) #

    // f expr is 6:+9 do this9 then exit the P loo elseif

    ( expr!):

    // f expr is P8S+9 and expr! is 6:+9 do this9 then exit the

    loo

    else#

    // f all expr"s are P8S+9 do this9 then exit endif;

    Switch

    s%itch (exr){ case value:

    // 3o this if value &atchesrea; case

    value!:// 3o this if value! &atchesrea;

    defalt# // ,otional.// 3o this if no other cases &atchF 3oes not ha"e to e at the end rea;

    }

    expr- A$string, $integer,or$floatto be compared against

    Aswitchevaluates theexpragainst any number ofcasesor options, specifying the

    behavior for eachcase.Cases can be 'stacked' to allow the same portion of code to be evaluated for different

    cases:

    s%itch ( expr)

    { case value:

    case value!:

    // 3o this if value or value! &atches

    }

    Theswitchis evaluated line-by-line, and therefore if there was nobreakcommand,

    thecasedeclaration would effectively be ignored and the code would continue to be

    processed until theswitchends or abreak;is reached.

    $x = 1;

    s%itch ($x) {

    case 1#echo '1'; //

  • 8/12/2019 Php for Files

    29/176

    PHP Reference: Beginner to Intermediate PHP5

    Examples:

    $x = ?; s%itch

    ($x) { case 1#

    echo '1';

    rea;

    case ?#

    echo '?';

    rea;

    case A#

    echo 'A';

    rea;

    }

    $x = 'ho%dy';s%itch ($x)

    { case 'hi'#

    echo 'Hi there';

    rea;

    defalt# // an e any%here9 all cases e"alated efore it is sed

    echo 'Greetin*s';

    rea; case

    'hello'#

    echo 'Hello there';

    rea;

    }

    Greetin*s

    See Also:

    break -Stops a loop and exits regardless of if the statement evaluates as true

    . . .

    Alternative syntax for aswitchstatement:

    s%itch ( expr):

    case value:

    // 3o this if value &atches

    rea; case

    value!:

    // 3o this if value! &atches

    rea;

    defalt# // ,otional.

    // 3o this if no other cases &atchF 3oes not ha"e to e at the end rea;

    ends%itch;

    while

    %hile ( expr) {

    // f expr is 6:+9 do this9 then e"alate expr a*ain

    }

    "9

  • 8/12/2019 Php for Files

    30/176

    PHP Reference: Beginner to Intermediate PHP5

    Thewhileloop checks theexprand if it evaluates as true, the script runs through the

    entire contents of thewhileuntil it finishes, then it evaluates theexpragain and

    repeats until theexprevaluates as false.

    Example:

    $x = 1;%hile ($x 0= A){

    echo 4$x9 4;$x@@; // incre&ents $x y addin* 1F ShortNhand "ersion

    }

    19 ?9 A9

    See Also:

    do-while -Same aswhile,except theexpris evaluated after the first actionbreak -

    Stops a loop and exits regardless of a TRUE statement evaluationcontinue -Stops

    the iteration of the loop, and theexpris evaluated again

    Alternative syntax for awhilestatement:

    %hile (expr) #

    // f expr is 6:+9 do this9 then e"alate expr a*ain

    end%hile;

    do-while

    do {

    // 3o this} %hile ( expr);

    Thedo-whileloop performs whatever is inside thedostatement, checks theexpr,then

    if it evaluates as TRUE, runs through the entire contents of thedountil it finishes,

    evaluating theexpragain, and repeating until theexprevaluates as FALSE.

    Example:

    $x = 1;

    do {

    echo 4$x9 4;

    $x@@; // Eaes $x = ?9 therefore the %hile %ill e"alate as false } %hile

    ($x 0= 1);

    See Also:

    while -Similar todo-while,except theexpris evaluated first

    break -Stops a loop and exits regardless of if the statement evaluates as true

    continue -Stops the iteration of the loop, and theexpris evaluated again

    30

  • 8/12/2019 Php for Files

    31/176

    PHP Reference: Beginner to Intermediate PHP5

    for

    for (expr#; expr!; expr$) {// f expr! is 6:+9 do this

    }

    When started, theforloop executesexprlonce at the beginning. Next,expr2is

    evaluated. Ifexpr2is true, the code inside theforloop is executed. When theforloop

    reaches the end,expr3is executed before looping and checkingexpr2again.

    Example:

    for ($x = 1; $x 0= B; $x@@){ echo $x;

    }

    1?AB

    See Also:

    break -Stops theforloop and exits it immediately

    continue -Stops the current iteration of theforloop, andexpr3is executed before

    checkingexpr2again

    Alternative s%nta( ,or aforstatement:for ( expr# ; expr!; expr$):

    // f expr! is 6:+9 do thisendfor;

    An example ofcontinueandbreakin aforloop:

    for ($"=-;$"0=1-;$"@@){ echo

    $";

    if ($" == B)

    { contine;

    }if ($" == J)

    { rea;

    }echo

    }

    -919?9A99BL9I9J

    foreach

    foreach ($array as %value) {// 3o so&ethin*

    }// nother for&9 for eys and "alesforeach ($array as %&e' = %value) { // 3oso&ethin*

    }

    31

  • 8/12/2019 Php for Files

    32/176

    PHP Reference: Beginner to Intermediate PHP5

    Theforeachloop goes through all items in an array, assigning a temporary variable

    name forvalueand, if chosen, thekeyas well so they can be used within the executed

    code inside the loop.

    Examples:

    $array = array('ohn' = ?-9 'ane' = ?9 'oseh' = ?J);foreach ($array as $"ale){ echo 4$"ale9 4;}

    ?-9 ?9?J9foreach ($array as $na&e = $a*e){

    echo 4$na&e N $a*e4;

    echo '0r /'; // TH6E8}

    for a line rea

    ohn N ?-

    ane N ?

    oseh N ?J

    See Also:

    Pass by Reference -Using the ampersand ( & ) to alter an array throughforeach

    break [$integer]

    $integer- [optional] Specifies the number of nested loops to break out of

    Exits and stops execution of the current (default) for,foreach, while, do-while,orswitch

    loop.

    Example:

    $conter = -;

    %hile (1 == 1){ // Will rn fore"er

    %hile (- == -){ // Will also rn fore"er

    $conter@@; // ncre&ent $conter ls 1 echo

    $conter; if ($conter == B){ rea ?;

    }

    }

    echo 'Pirst %hile loo'; //

  • 8/12/2019 Php for Files

    33/176

    PHP Reference: Beginner to Intermediate PHP5

    continue [$integer]

    $integer- [optional] Specifies the number of nested loops to skip out ofNote:The

    $integerdoes 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 loop(

    3.

    Example:

    for ($x=1;$x0=1-;$x@@){ if

    ($x == B) { contine;

    } // 6he echo ne"er occrs if $x == B

    echo $x;

    }

    1?ALIJK1-

    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 asexit()

    ordie().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$variableas part of a function

    exit() -Terminate the current script immediately

    include(file)

    file-$string

    Include and evaluate thefileas 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:

    inclde('so&efileFinc');

    3. In te case o, aswitch, continue as te same e,,ect asbrea!

    4. unctions soul& onl% be inclu&e& once# Consi&er usin inclu&eonce or re6uireonce

    33

  • 8/12/2019 Php for Files

    34/176

    PHP Reference: Beginner to Intermediate PHP5

    include_once(file)

    file-$string

    Include and evaluate thefileas part of the current script/page. If the file has already

    been included, it will ignore the request. This is an easy way to store common

    variables, functions, or lines of HTML that will be included by multiple scripts/pages.

    Failure of the function generates an error and terminates the script immediately.

    Example:incldeDonce('so&efileFh');

    require(file)

    file-$string

    Include and evaluate thefileas part of the current script/page. This is an easy way to

    store common variables, functions5, or lines of HTML that will be included by

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

    Example:

    re>ire('so&efileFht&');

    require_once(file)

    file-$string

    Include and evaluate thefileas part of the current script/page. If the file has already

    been included, it will ignore the request. This is an easy way to store common

    variables, functions, or lines of HTML that will be included by multiple scripts/pages.

    Failure of the function generates an error and terminates the script immediately.

    Example:

    re>ireDonce('so&efileFh ' );

    5 unctions soul& onl% be inclu&e& once# Consi&er usin re6uireonce

    34

  • 8/12/2019 Php for Files

    35/176

    PHP Reference: Beginner to Intermediate PHP5

    Global Variables

    While some global variables can be created through the use ofdefine(),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, dependingon the current script and environment.

    $_SERVER

    $_SERVER['HTTP_USER_AGENT'] - Browser description from header,H66QDS+:DG+

  • 8/12/2019 Php for Files

    36/176

    PHP Reference: Beginner to Intermediate PHP5

    $_REQUEST

    Includes all variables provided by$_GET, $_POST,and$_COOKIE

    $_POST

    Includes all variables submitted through HTTP POST, such as an HTML form with

    action="post".

    $_GET

    Includes all variables submitted through the query string, either manually or from a

    form with action="get".

    htt#//%%%F exa&le F co&/testF h>ery="ale

    // tt of rintDr($DG+6) of the ao"e :8 exa&le rray

    ( ,>ery. = "ale )

    $_SESSION

    Variables assigned to the current session.

    $_COOKIE

    Any cookies stored for the current website. Only visible after the page was reloaded

    if it was just set usingsetcookie().

    See Also:

    setcookie() -Assigning and deleting cookies

    $_FILES

    Variables provided to the script via POST uploads.

    $_ENV

    A collection of variables about the server environment.

    $GLOBALS

    Contains a reference for all variables, global or otherwise, in the script.

    3$

    http://www/http://www/
  • 8/12/2019 Php for Files

    37/176

    PHP Reference: Beginner to Intermediate PHP5

    Variable Functions

    The following functions check details about variables themselves, rather

    than addressing a specific aspect of atypeof variable. Put another way, you don't

    want to know what type of elephant you have, just that it is an elephant, and it is

    about to trample you. Too much? Oh well, here we go again.

    empty($variable)

    Determine whether the$variableis empty. Returns TRUE if the$variableis:

    '' - Empty$string

    0 - For an$integer

    '0' - For a$string

    array() - For an$array

    NULL

    FALSE

    An undeclared variable

    Example:

    $strin* = 'Hello';

    $array = array();"arDd&( e&ty($strin*)9 e&ty($array)9 e&ty($3oes

  • 8/12/2019 Php for Files

    38/176

    PHP Reference: Beginner to Intermediate PHP5

    Example:

    $strin* = 1 1 ;

    $inte*er = -;

    $array =

  • 8/12/2019 Php for Files

    39/176

    PHP Reference: Beginner to Intermediate PHP5

    Example:

    $array = array();$array? = array( 'one'9 't%o'9 'three' );

    "arDd&( isDarray($array)9 isDarray($array?) );

    ool(tre) ool(tre)

    is_int($variable)

    Also known as:is_integer()

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

    Example:

    $int = -;

    $strin* = '-';

    "arDd&( isDint($int)9 isDint($strin*) );

    ool(tre) ool(false)

    is_string($variable)

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

    Example:

    $int = -;

    $strin* = '-' ;

    "arDd&( isDstrin*($int)9 isDstrin*($strin*) );

    ool(false) ool(tre)

    is_numeric($variable)

    Determine whether the$variableis an integer or a numeric string(e.g."12"). If either

    is true, it will return TRUE.

    Example:

    $int = 1-; $strin*

    = '1-';

    "arDd&( isDn&eric($int)9 isDn&eric($strin*) );

    ool(tre) ool(tre)

    See Also:

    is_int() -Determine if a variable is an integeris_string() -Determine if a variable is an string

    39

  • 8/12/2019 Php for Files

    40/176

    Mario Lurig

    var_dump(expr [,...expr...])

    Accepts multiple expressions, separated by commas

    expr- A$variableor any expression that generates a result

    Shows the type of variable and its value in the following format:

    t'pe(value) // When e"alatin* a oolean9 inte*er9 or float strin*(length)

    value // When e"alatin* a strin* array(len*th) { value } // When

    e"alatin* an array

    Example:

    $inte*er = 1-; $strin* =

    'Hello'; $array =

    array( 'one' );

    "arDd&( $inte*er9 $strin*9 $array9 isDstrin*($strin*) );

    int(1-) strin*(B) 4Hello4 array(1) { ,-.= strin*(A) 4one4 }

    ool(tre)

    See Also:

    echo -Prints the value of a$scalar

    . . .

    Surroun&in te var_dump()'it te / tas 2)re 2)re 'ill )resent te out)ut o,

    multi)le e()ressions in a more uman rea&able ,ormat#

    // sin* the sa&e "ariales as ao"e echo

    '0re';

    "arDd&( $inte*er9 $strin*9 $array9 isDstrin*($strin*) );

    echo '0/re';

    print_r($variable)

    Output the contents of$variable6.Typically used to display the contents of an array.

    Example:

    $array = array( 'le'9 'ran*e'9 'Eelon' );rintDr($array);

    rray ( ,-. = le ,1. = ran*e ,?. = Eelon )

    See Also:

    echo -Display the value of a$scalar

    $ I, Svariable isboolean+ ;

  • 8/12/2019 Php for Files

    41/176

    PHP Reference: Beginner to Intermediate PHP5.

    . .

    If you add the HTML tags around the output, formatting will be easier

    to follow.

    $array = array( 'le'9 'ran*e'9 'Eelon' );

    echo '0re'; rintDr($array); echo '0/re';

    rray

    (,-. = le,1. = ran*e,?. = Eelon

    )

    Here is a quick function to do this easily:,fnction rerint($array){

    echo '0re'; rintDr ($array); echo '0/re'; lserialize(value)

    Converts thevalueto a storable representation in a$string.

    Example:

    $array = array( 'one'9 't%o'9 'three' );

    $ott = serialiVe($array); echo$ott;

    a#A#{i#-;s#A#4one4;i#1;s#A#4t%o4;i#?;s#B#4three4;}

    See Also:

    unserialize() -Convert a serialized string back into its originalvalue

    If adding the serialized data to a MySQL database, you will need to escape some

    characters usingaddslashes()and then remove them again withstripslashes()when

    recovering the value from the database.

    $array = array( 'one'9 't%o'9 'three' );$dDready = addslashes(serialiVe($array));

    // add $dDready to yor dataase (code not inclded here) //

    retrie"e it fro& the dataase (code not inclded here) $nor&al =

    nserialiVe(strislashes($dDready));

    41

  • 8/12/2019 Php for Files

    42/176

    Mario Lurig

    unserialize($string)

    Converts a serialized$stringback into its original value.Example:

    $array = array( 'one'9 't%o'9 'three' );$ott = serialiVe($array);

    echo '0re ' ;

    "arDd&($ott);

    rintDr( nserialiVe($ott) );

    echo '0/re ' ;

    strin*(B-) 4a#A#{i#-;s#A#4one4;i#1;s#A#4t%o4;i#?;s#B#4three4;}4

    rray

    (,-. = one,1. = t%o,?. = three

    )

    See Also:

    serialize() -Convert avalueto a storable representation in a$string

    floatval($scalar)

    Returns the float value of the$scalar.

    Note:If the$scalaris a string starting with integers, characters after the integers will be

    stripped out.

    Example:

    $float = 1FA;

    $strin* = 41Bthe %ords4;

    $strin*? = 4--?B4;

    "arDd& ( float"al($float)9 float"al($strin*)9 float"al($strin*?) );

    float(1FA) float(1B) float(?B)

    . . .

    As in the example above, if a string starts with integers and has trailing characters,

    you can convert this to a float with this command. However, if you intend to use this

    function to retrieve the string equivalent, any leading zeros will be erased. Be careful!

    4"

  • 8/12/2019 Php for Files

    43/176

    PHP Reference: Beginner to Intermediate PHP5

    String Functions

    If you were a cat, string functions would be the cat's meow, all puns

    intended. Besides being a large part of your PHP code, they provide much of the

    functionality to identify and alter your data into other formats, such as arrays.

    addslashes($string)

    Adds backslashes (escape string) to items within$stringto make it safe for database

    queries. Effects single quotes ( ' ), double quotes ( " ), backslashes ( \ ), and the NUL

    byte.

    Example:

    $strin* = ' 6o& said9 4Earcs is &ad!4'; echo

    $strin*;

    $strin* = addslashes($strin*); echo

    $strin*;

    6o& said9 4Earcs is &ad!4 6o& said9 54Earcs is &ad!54

    See Also:get_magic_quotes_gpc -Server setting for automatically applying addslashes to

    GET/POST/COOKIE data

    stripslashes() -Remove the backslashes created byaddslashes()

    stripslashes($string)

    Removes backslashes (escape string) from items within$stringadded

    throughaddslashes()ormagic_quotes_gpc.

    Example:

    $strin* = ' 6o& said9 4Earcs is &ad!4';

    $strin* = addslashes ($strin*); echo $strin*;$strin* = strislashes($strin*);

    echo $strin*;

    6o& said9 54Earcs is &ad!54 6o& said9 4Earcs is &ad!4

    43

  • 8/12/2019 Php for Files

    44/176

    PHP Reference: Beginner to Intermediate PHP5

    See Also:

    get_magic_quotes_gpc -Server setting for automatically applying

    addslashes to GET/POST/COOKIE data

    addslashes() -Adds backslashes to make a string safe for database queries

    chunk_split($string [,length][,endstring])

    length- [optional]$integerdefault:76

    endstring- [optional]$stringdefault:"\r\n" (carriage return and new line)

    Splits$string

    into sections oflengthcharacters, every section is terminated with theendstring.Evaluates only the character length to generate the resulting string.

    Example:

    $strin* = 'Hello

  • 8/12/2019 Php for Files

    45/176

    PHP Reference: Beginner to Intermediate PHP5

    $strin* = 'Hello

  • 8/12/2019 Php for Files

    46/176

    PHP Reference: Beginner to Intermediate PHP5

    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

    5. - Returns an array with the count for all characters with at least one

    instance in$string

    6. - Returns an array with the count for all characters with zero

    instances

    7. - Returns a string of all characters contained within$string

    8. - Returns a string of all characters not contained within$string

    Checks$stringfor instances of all ASCII characters and counts the number of times

    that a character is included within the string. Output varies depending onmode.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:

    $strin* = 'Hello';

    $array = contDchars($strin*9 1);

    echo '0re'; // ired9 inclded for easier readaility

    rintDr($array);

    rray

    (

    ,I?. = 1

    ,1-1. = 1

    ,1-J. = ?

    ,111. = 1

    strin*() 4Helo4

    See Also:

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

    4$

    $sedcharacters = contDchars($strin*9 A);

    "arDd&($sedcharacters);

    )

    foreach ($array as $ey = $"ale){

    $char = chr($ey); // haracter reresented y the yteN"ale

    $chararray,$char. = $"ale; // Eae ne% array %ith characters

    }rintDr($chararray);

    rray(

    ,H. = 1,e. = 1,l. = ?

    ,o.) = 1

  • 8/12/2019 Php for Files

    47/176

    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(I?); H

    echoargument[,...argument...]

    Accepts multiple arguments separated by a comma argument- A$scalaror function

    with scalar outputOutputs the value of theargumentto the user.

    Example:

    echo 'Hello

    ' ; Hello

    printargument

    argument- A$scalaror function with scalar outputOutputs the value of the

    argumentto the user, always returns 1. Useecho()instead.

    Example:

    $x = rint 'Hello';

    rint $x;

    Hello

    explode(delimiter,$string [,limit])

    delimiter-$string,if set to '', explode will return FALSElimit-

    [optional]$integer,default:no limit

    Returns an array of strings created by searching through$stringand separating it

    by using the provideddelimiteras the separation point.Limitsets the maximum

    number of elements, with the last element of the array being the remainder of the

    string}7

    7

    8

    .

    47

    1. Sboolean is re)resente& b% 1 ;

  • 8/12/2019 Php for Files

    48/176

    PHP Reference: Beginner to Intermediate PHP5

    rray

    (,-. = -?

    ,1. = -1N1KJ-

    See Also:

    implode() -Creates a string from array elements, using a joining string

    . . .

    As shown above, explode can be used to break apart common language syntax, such

    as separating a paragraph submitted by a user into its individual sentences, or

    allowing a user to submit tags for a particular item, separated by commas, and then

    explode()those items for database storage.

    48

    Example:

    $array = exlode.'N'9 $exlode&e9 ?); // 8i&it to ? ele&entsrintDr($array);

    $exlode&e = '-?N-1N1KJ-';

    $array = exlode.'N'9 $exlode&e); // dash (N) is the deli&iter

    echo '0re'; // Por easier readaility rintDr($array);

    rray(

    ,-. = -?,1. = -1,?. = 1KJ-

    im lode(limiter, $arra)limiter-$string

    Returns a string containing the contents of$arrayjoined by the providedlimiter.

    Example:

    $array = array. 'Hello'9 'World'9 '!' );

    $strin* = i&lode.' '9 $array); // sin* a sace as the limiter echo

    $strin*;

    Hello World !

    See Also:

    explode() -Separate a string into an array using a specific delimiting string

  • 8/12/2019 Php for Files

    49/176

    PHP Reference: Beginner to Intermediate PHP5

    sprintfformatting, inputs [, ...inputs...]

    Accepts multiple inputs to be used when specified in formatting

    formatting-$stringspecific formatting string, explained belowinputs-$scalar(s) to

    be formatted

    Returns a formatted stringformatting,using theinputsto dynamically input their

    values into the formatted string using a preset set of rules, specified below.

    The following is the available nomenclature for theformattinginput.

    49

    Every time an input is expected to be used and evaluated as part of the formatted

    string, it is preceded by a percent sign ( % ), followed by the specifiers/rules:

    Note:All specifiers, excluding thetypespecifier, are optional.

    Asignspecifier. Placing a plus sign ( + ) forces negative AND positive signsto be visible (only negative values are specified by

    default).

    Apaddingspecifier. The default is a space, and does not need to bespecified. A zero ( 0 ) can be used as well without any secondary notation. If

    any other character is to be used, it should be preceded with a single quote

    ( ' ).

    Analignmentspecifier. The default is right-justified (thus padding is placedon the left of the string). Placing a dash/subtract ( - ) will set it to left-

    justified.

    Awidthspecifier. This integer determines the minimum length incharacters the output should be. When combined with padding, the

    specified width minus the input's length determines the number of padded

    characters that will be added.

    Aprecisionspecifier. A period ( . ) followed by an integer, sets the numberof decimal places that should be output for a float. If used on a string, it sets

    a maximum character limit for the output.

    Atypespecifier:

    %- a literal percent sign, thus would be written %% to display a percent

    sign in the formatting string

    b- the input should be an integer, a binary number is the output.

  • 8/12/2019 Php for Files

    50/176

  • 8/12/2019 Php for Files

    51/176

    PHP Reference: Beginner to Intermediate PHP5Usingpaddingand

    widthusing a custom character, the asterisk ( * )

    $endofass%ord = '%ord';

    $ott = srintf(4or ass%ord# O'7Js49 $endofass%ord); echo

    $ott;

    or ass%ord# 7777%ord

    Usingpadding, alignment(left), andwidth

    $endofass%ord = '%ord';

    $ott = srintf(4or ass%ord# O'7NJs49 $endofass%ord); echo $ott;

    or ass%ord# %ord7777

    Using theprecisionspecifier

    $scientific = 1F?eA;

    echo srintf(46hree deci&al laces# OFAe49 $scientific); 6hree

    deci&al laces# 1F?--e@A $float = 1F?eA;

    echo srintf(46%o deci&al laces# OF?f49 $float); 6%o

    deci&al laces# 1?--F-- $strin* = 'Hello World!';

    echo srintf(4tNoff after characters# OFs49 $strin*); tNoff

    after characters# Hell

    See Also:

    printf() -prints a formatted string results rather than simply returning themsscanf() -

    Parses a string through a formatted string, reverse ofsprintf()

    ? @ ? ? @ ? ? @ ?

    For MySQL security, you can usesprintf()to force user input to have a

    maximum length and be valid for the structure of your database. Use the

    precisionspecifier to automatically parse the string submitted by GET or

    pOST._____________________________________________________________________

    printf(formatting, inputs[, ...inputs... ]

    Accepts multiple inputs to be used when specified in formatting

    formatting-$stringspecific formatting string.Seesprintf()for nomenclature inputs-

    $scalar(s) to be formatted

    Prints a formatted stringformatting,using theinputsto dynamically input their values

    into the formatted string using a preset set of rules.Note:Seesprintf()for rules for

    formatting strings.

    51

  • 8/12/2019 Php for Files

    52/176

    Mario Lurig

    Example:

    $strin* = 'ies';

    rintf(4 thin Os are cteF49 $strin*);

    thin ies are cteF

    See Also:

    sprintf() -Returns the formatted string, explains rules/nomenclature

    sscanf($string,formatting[, ...outputs... ]

    Accepts multiple [optional] outputs, but changes the behavior of the function

    Examines the given$stringand parses it based on the expectedformatting.Returns an

    array when nooutputsare included. Ifoutputsare included, they specify by reference

    the variable names to assign the formatted contents.Note:Seesprintf)for rules for

    formatting strings -typespecifiers.

    Examples:

    See Also:

    sprintf() -Reverse ofsscanf()and provides explanation of formatting stringslist() -

    Assigns the values of an array to variable names

    |htmlspecialchars($string [,quotes_flag][,character_set])

    quotes_flag- [optional]$stringdefault:ENT_COMPAT (double quotes only) Other

    values: ENT_QUOTES (both single and double quotes)

    ENT_NOQUOTES (neither double nor single)

    character_set- [optional]$stringdefault:ISO-8859-1

    Converts some characters in$stringwith special meaning in HTML to their safe

    HTML entities. This includes (but may be limited by some optional

    5"

    $strin* = '1?/1/1KJ-' ;

    $ottsDcont = sscanf($strin*9 4Od/Od/Od49 $&onth9 $day9 $year);

    "arDd& ($&onth9 $day9 $year);

    int(1?) int(1) int(1KJ-)

    $strin* = '1?/1/1KJ-' ; $array =

    sscanf($strin*9 4Od/Od/Od4); echo

    '0re'; // Por i&ro"ed readaility

    rintDr($array);

    rray

    (,-. = 1?,1. = 1

    ,?.) = 1KJ-

  • 8/12/2019 Php for Files

    53/176

    PHP Reference: Beginner to Intermediate PHP5

    flags): double quotes ( " ), single quotes ( ' ), greater than ( > ), less than ( < ), and

    ampersand ( & ).

    Example:

    $strin* = '0stron*Hello U World!0/stron*0r /'; echo

    ht&lsecialchars($strin*);

    HTML source code:

    Ult;stron*U*t;Hello Ua&; World!Ult;/stron*U*t;Ult;r /U*t;

    See Also:htmlspecialchars_decode()- Reverses the effect ofhtmlspecialchars()

    htmlentities()- Effects all HTML entities, not just the five above

    |htmlspecialchars_decode($string [,quotes_flag])

    quotes_flag- [optional]$stringdefault:ENT_COMPAT (double quotes only) Other

    values: ENT_QUOTES (both single and double quotes)

    ENT_NOQUOTES (neither double nor single)

    Converts HTML entities back to the character representation in$string.This includes

    (but may be limited by some optional flags): double quotes ( " ), single quotes ( ' ),

    greater than ( > ), less than ( < ), and ampersand ( & ).

    Example:

    $strin* = 'Ult;stron*U*t;Hello Ua&; World!';echo ht&lsecialcharsDdecode($strin*);

    HTML source code:

    0stron*Hello U World!

    See Also:

    htmlspecialchars()- Converts the five items above into their HTML entities

    html_entity_decode()- Effects all HTML entities, not just the five above

    |htmlentities($string [,quotes_flag][,character_set])

    quotes_flag- [optional]$stringdefault:ENT_COMPAT (double quotes only) Other

    values: ENT_QUOTES (both single and double quotes)

    ENT_NOQUOTES (neither double nor single)

    character_set- [optional]$stringdefault:ISO-8859-1

    Converts some characters in$stringwith special meaning in HTML to their safe

    HTML entities. This includes (but may be limited by some optional flags): double

    quotes ( " ), single quotes ( ' ), greater than ( > ), less than ( < ), and ampersand ( & ).

    53

  • 8/12/2019 Php for Files

    54/176

    PHP Reference: Beginner to Intermediate PHP5

    Example:

    $strin* = 40stron*'Hello World!'4; echo

    ht&lentities($strin*9 +otes not con"erted

    HTML source code:

    0stron*U[-AK;Hello World!U[-AK;

    See Also:

    htmlentities()- Converts all HTML entities

    htmlspecialchars_decode()- Decodes five specific HTML entities

    trim($string [,characters])

    characters- [optional]$string

    Remove from the beginning and end of$stringthe following characters whencharactersis not included: whitespace (' '), tab (\t), new line (\n), carriage return (\r),

    NUL byte (\0), and the vertical tab (\x0B). Ifcharactersis included, that list is used

    instead9.

    Note:Once a character not from the list is reached, trimming halts.

    Examples:

    $strin* = 4 5n Hello World! 5t5t4;

    echo tri&($strin*);

    54

    9 *itin characters, a &ouble )erio& ## can s)eci,% a rane (e.g. a## is a trou

  • 8/12/2019 Php for Files

    55/176

    PHP Reference: Beginner to Intermediate PHP5

    echo tri&($strin*9 4 5t5n!r4);

    // r %ill not e re&o"ed ecase d is not in the list Hello

    World

    echo tri&($strin*9 4 5t5n!dFFr4); // ran*e of d thro*h r (lo%ercase) Hello W

    See Also:

    ltrim() -Trim only from the beginning of the stringrtrim() -

    Trim only from the end of the string

    ltrim($string [,characters])

    characters- [optional]$string

    Remove from the beginning of$stringthe following characters whencharactersis not

    included: whitespace (" "), tab (\t), new line (\n), carriage return (\r), NUL byte (\0),

    and the vertical tab (\x0B). Ifcharactersis included, that list is used instead10.

    Note:Once a character not from the list is reached, trimming halts. Examples:

    $strin* = 4 5n Hello World!4;

    echo ltri&($strin*);

    echo tri&($strin*9 4 5nFFHaFFV4);

    // ll caital letters et%een and H9 and all lo%ercase letters World!

    See Also:

    trim() -Trim from the beginning and the end of the stringrtrim() -Trim only from the end of the string

    rtrim($string [,characters])

    Also known aschop()characters-

    [optional]$string

    Remove from the end of$stringthe following characters whencharactersis not

    included: whitespace (" "), tab (\t), new line (\n), carriage return (\r), NUL byte (\0),

    and the vertical tab (\x0B). Ifcharactersis included, that list is used instead10.

    Note:Once a character not from the list is reached, trimming halts.

    10 *itin characters, a &ouble )erio& can s)eci,% a rane (e.g. a## is a trou

    55

  • 8/12/2019 Php for Files

    56/176

    Mario Lurig

    Examples:

    $strin* = 4Hello World?! 5t5t4; echo

    tri&($strin*);

    Hello World?!

    echo tri&($strin*9 4 5t!-FFK4);

    // :an*e inclded is all n&ers et%een - and K Hello

    World

    See Also:ltrim() -Trim only from the beginning of the stringtrim() -Trim

    from the beginning and the end of the string

    crypt($string [,salt])

    salt- [optional]$string

    Performs a one-way hashing encryption on$stringusing an algorithm specified by

    the system11. Thesaltcan be used to generate a stronger encryption, but when not

    specified and generated by the system, it will be created once per run of the script.

    Example:$ass%ord = '&yass%ord';echo cryt($ass%ord); // tt %ill "ary

    See Also:

    md5() -MD5 algorithm based encryption, portable, more secure, commonly used

    sha1() -Shal algorithm based encryption, portable, most secure

    md5($string [,raw_flag])

    raw_flag- [optional]$booleandefault:FALSE, 32-character hexadecimal

    Performs a one-way hashing encryption on$stringusing the MD5 Message-Digest

    Algorithm. If theraw_flagis set to TRUE, it returns a raw binary format with a

    length of 16 characters.

    Example:

    $ass%ord = '&yass%ord';

    echo &dB($ass%ord);

    A J1KdIeeaK? L-aBcJBcJBAe

    5$

    11 So,t'are movin bet'een )lat,orms ma% ave &i,,erent encr%)tions+ an& tus 'ill cause

    )roblems 'it com)atibilit%# Best to use m&5 or sa1 instea& ,or )ortabilit%

  • 8/12/2019 Php for Files

    57/176

    PHP Reference: Beginner to Intermediate PHP5

    See Also:

    sha1() -Sha1 algorithm based encryption

    . . .

    For better security in storing user passwords, the use of a salt should be considered.

    The salt is basically a string added onto the supplied$stringto increase its length

    and complexity. In the case of user passwords, it would be randomly created by the

    system then saved to the database as a separate entry in the database from the

    password for that user. This helps protect against reverse md5 dictionary attacks.

    $ass%ord = 'ass%ord'; // Xery ad ass%ord

    $salt = sstr(&dB(ni>id(&tDrand()9 6:+))9 -9 B); // B char9 salt

    $saltedDass%ordDhash = &dB($salt F &dB($ass%ord)); echo

    $saltedDass%ordDhash; // tt "aries

    d1?A KdccLe-1I BI ?eaLfedBdf-dLe-Ie

    57

    md5_lelename [, raw_a])filename-$string

    raw_flag- [optional]$booleandefault:FALSE, 32-character hexadecimal

    Generates the MD5 hash of a file withfilename.If theraw_flagis set to TRUE, it

    returns a raw binary format with a length of 16 characters.

    Example:

    $hash = &dBDfile('so&efileFtxt');

    See Also:

    md5() -MD5 algorithm based encryption for a string

    sha1($string [,raw_flag])raw_flag- [optional]$booleandefault:FALSE, 40-character hexadecimal

    Performs a one-way hashing encryption on$stringusing the US Secure Hash

    Algorithm. If the raw_flag is set to TRUE, it returns a raw binary format with

    a length of 20.

    Example:

    $ass%ord = '&yass%ord';

    echo sha1($ass%ord);

    K1dfdKdd1KJaffcBc1KcdJceLdAA Jfde I -e?

  • 8/12/2019 Php for Files

    58/176

    PHP Reference: Beginner to Intermediate PHP5

    See Also:

    md5() -MD5 algorithm based encryption, commonly used

    ? @ ? ? @ ? ? @ ?

    please seemd5()tip for adding a salt to a password for extra security"

    58

    sha1_file(lename[,raw_ag])filename-$string

    raw_flag- [optional]$booleandefault:FALSE, 40-character hexadecimal

    Generates the Sha1 hash of a file withfilename.If the raw_flag is set to TRUE, it

    returns a raw binary format with a length of 20.

    Example:

    $hash = sha1Dfile('so&efileFtxt');

    See Also:

    sha1() -Sha1 algorithm based encryption for a string

    number_format( $float [,decimals][,decimal_point, thousand_separator]decimals- [optional]$integerdefault:0, no decimal places

    decimal_point- [optional]$stringdefault:period ( . )

    thousand_separator- [optional]$stringdefault:comma ( , )

    Format the$floatwith thousand separating and decimal places, if specified.Note:

    Rounding occurs if the float has more values than the formatting specifies.

    Examples:

    $float = 1?ABLIFJK1;

    echo n&erDfor&at($float);

    19?A9BLJ

    echo n&erDfor&at($float9 ?); // S notation

    19?A9BLIFJK

    echo n&erDfor&at($float9 ?9 4 4); // Prench for&attin*

    1 ?A BLI9JK

    nl2br($string)Replaces all instances of the new line ( \n ) formatting character in$stringwith

    the XHTML line break
    .

  • 8/12/2019 Php for Files

    59/176

    PHP Reference: Beginner to Intermediate PHP5

    Example:

    $strin* = 4Hello5nWorld4;

    echo nl?r($strin*);

    HTML Source Code:

    Hello0r /World

    Standard output:

    Horld

    parse_str($string [, $array])

    Examines$stringas a query string and assigns the variables with names equal to the

    query's key, then assigning values equal to the query's value. If$arraywas specified,

    query variables will be assigned to an array instead with the same key => value

    association.

    Note:Output is affected by the magic_quotes_gpc setting the same as $_GET. Examples:

    $>eryDstrin* = 'ey="aleUcolor=red';

    arseDstr($>eryDstrin*);

    echo 45$ey e>als $ey9 and 5$color e>als $color4;

    $ey e>als "ale9 and $color e>als red

    $>eryDstrin* = 4ey="aleUcolor='red'4;

    arseDstr($>eryDstrin*9 $array);

    echo '0re'; // Por easier readaility

    rintDr($array);

    Without magic_quotes_gpc enabled:rray

    (

    ,ey. = "ale

    ,color. = 'red'

    With magic_quotes_gpc enabled:

    rray

    (

    ,ey. = "ale

    ,color. = 5'red5'

    See Also:

    get_magic_quotes_gpc -Check if magic quotes is enabledlist() -

    Assign contents of an array to variables

    59

  • 8/12/2019 Php for Files

    60/176

    PHP Reference: Beginner to Intermediate PHP5

    This is a handy way to easily convert all the query submitted keys/values from

    $_SERVER['QUERY_STRING'] into variables using the following:

    arse str($ S+:X+:,1 2+: S6:

  • 8/12/2019 Php for Files

    61/176

    PHP Reference: Beginner to Intermediate PHP5

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

    $relace = 'x'; $strin* =

    4Hello4;

    $ne%strin* = strDrelace($findarray9 $relace9 $strin*); echo

    $ne%strin*;

    See Also:

    str_ireplace() -Case-insensitive version ofstr_replace()

    strtr()- Simplified variation that also does not repeat onfind/replace

    str_ireplacefind,replace, subject [, count])

    find-$stringor$array

    replace-$stringor$array

    subject-$stringor$array

    count- [optional]variable name - $integer

    Replaces all instances offindwithreplacewithinsubject.If subject is an array, thefindandreplaceoccurs 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 infindand

    replacing it with the first entry inreplace,then repeating with the next set of entries. If

    there are more values in thefindarray than thereplacearray, an empty string ('') is

    used as the replacement. Iffindis an array andreplaceis a string,replaceis used for

    every entry infind.

    The optionalcountvariable will be set with the total number of replacements that

    occurred.

    Note:This function is case-insensitive.

    Example:

    $ne%strin* = strDirelace('find'9 'relace'9 ' %ill P

  • 8/12/2019 Php for Files

    62/176

    Mario Lurig

    strtr($string,find, replace)

    strtr($string,replace_array)

    find-$stringreplace

    -$string

    replace_array-$array,associativefind=>replace

    This function behaves differently if presented with either three arguments (single

    find/replace) or two arguments (uses an array of find/replace). With three

    arguments, all instances offindinside of$stringare replaced withreplace.With two

    arguments, each entry ofreplace_arrayis processed so that the key is replaced with the

    value.

    Note:Unlikestr_replace(),only the original values of$stringwill be subject to the

    find/replace.

    Example:

    echo strtr(' lie do*s'9 'do*'9 'cat');

    lie cats

    $array = array( 'find' = 'relace'9 'relace' = 'find');

    $strin* = ' %ill find and then relace'; $ne%strin* =

    strtr($strin*9 $array); echo $ne%strin*;

    %ill relace and then find

    See Also:

    str_replace() -A more flexible method of replacing items within a string

    substr($string,start [, length])

    start-$integer,if negative, starts counting from the end of$stringlength- [optional]

    $integerdefault:strlen($string)if negative, number of characters left off from the end

    of$string

    Returns only a portion of string starting with the character after numberstartand

    optionally forlengthcharacters long.

    Examples:

    echo sstr('1?ABLIJK-'9 A);

    BLIJK\

    echo sstr('1?ABLIJK-'9 NA9 1); echo

    sstr('1?ABLIJK-'9 NA9 N1);

    $"

  • 8/12/2019 Php for Files

    63/176

    PHP Reference: Beginner to Intermediate PHP5

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

    subject-$stringor$array

    replace-$string

    start-$integer,if negative, counts from the end of the stringlength-

    [optional]$integerdefault:strlen($string)

    Replaces text till the end of the string withinsubjectwithreplacestarting after

    character numberstart.Iflengthis specified, onlylengthnumber of characters after

    startare replaced withreplacewhenlengthis positive. Iflengthis negative, it represents

    the number of characters to stop replacing from the end of the string.

    Ifsubjectis an array, the function returns an array instead of a string, with the

    replacement processed on every entry in the array.

    Examples:

    $strin* = sstrDrelace('1?A B LI J K-'9 'hello'9 A);

    echo $strin*;

    1?Ahello

    echo sstrDrelace('1?ABLIJK-'9 'hello'9 A9 ?);

    $array = array('1?ABLIJK-'9 '-KJILBA?1'); $array =

    sstrDrelace($array9 'hello'9 NA9 N?);

    rintDr($array);

    rray ( ,-. = 1?ABLIhelloK- ,1. = - KJI LBhello?1 )

    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 numberlength-

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

    Returns the total number of instances ofneedleinhaystack.Ifstartis provided, it

    ignoresstartnumber of characters from the beginning. Iflengthis provided, it only

    checkslengthcharacters fromstart.

    Examples:

    echo sstrDcont('acdef9 'c');

    $3

  • 8/12/2019 Php for Files

    64/176

    Mario Lurig

    1

    echo

    sstrDcont('acdef9 'c'9 A);

    $4

  • 8/12/2019 Php for Files

    65/176

    PHP Reference: Beginner to Intermediate PHP5

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

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

    [optional]$stringdefault: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)Inserts

    into$stringspaces or the optionalpad_stringtill$stringispad_lengthnumber of

    characters long.

    Examples:

    $strin* = 'Hello';echo '0re'; // So refor&atted text is sho%n echo

    strDad($strin*9 I)9 '!';

    $strin* = 'Hello';

    echo strDad($strin*9 1-9 '['9 ?);

    [[Hello[[[

    See Also:

    sprintf()- More complex function designed for formatting strings

    str_repeat($string,multiplier)multiplier-$integer

    Returns a string with$stringrepeatedmultipliertimes.

    Example:

    echo strDreeat('1?A'9 A);

    str_shuffle($string)

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

    echo strDshffle('Hello World!');

    HreW! ollodl

    1" a&&in caracters are alternate& one-b%-one+ rit si&e ten le,t si&e

    $5

  • 8/12/2019 Php for Files

    66/176

    PHP Reference: Beginner to Intermediate PHP5

    str_split($string[, length])

    length- [optional]$integer

    Returns an array of$stringseparated by each character or the optionallengthnumber

    of characters.

    Examples:

    $array = strDslit('Hello');

    rintDr($array);

    rray ( ,-. = H ,1. = e ,?. = l ,A. = l ,. = o )

    $array = strDslit('Hello'9 ?);rintDr($array);

    rray ( ,-. = He ,1. = ll ,?. = 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 withposition

    =>word) characters- [optional]$string

    Counts the number of words inside$stringand returns that count by default (can be

    altered byoptions).Ifcharactersis present, it contains any characters that should be

    considered the same as a letter.

    Examples:

    $strin* = 'Welco&e to the Rn*le'; echo

    strD%ordDcont($strin*);

    $strin* = 'Welco&e to the RnA*le'; $%ithot =

    strD%ordDcont($strin*9 -); $%ithchar =

    strD%ordDcont($strin*9 -9 'A'); echo 4Withot#

    $%ithot9 Withhar# $%ithchar4;

    Withot# B9 Withhar#

    $$

    $strin* = 'Welco&e to the Rn*le'; echo

    '0re'; // Por easier readaility $array =

    strD%ordDcont($strin*9 1); rintDr($array);

    rray

    (,-. = Welco&e,1. = to,?. = the

  • 8/12/2019 Php for Files

    67/176

    PHP Reference: Beginner to Intermediate PHP5

    ,A. = Rn*le

    $array = strD%ordDcont($strin*9 ?);

    rintDr($array);

    rray

    (

    ,-. = Welco&e

    ,J. = to ,11.

    = the ,1B. =

    Rn*le

    )

    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 insideallowed_tags.

    Examples:

    $strin* = 406his is a ara*rahF 0/0stron*ay!0/stron*4; echo

    striDta*s($strin*)9 striDta*s($strin*9 '0');

    HTML Source Code:

    6his is a ara*rahF ay!

    echo striDta*s($strin*9 '0');

    06his is a ara*rahF 0/ay!

    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 ofhaystack)of the firstoccurrence ofneedleinhaystack.Ifstartis included, searching begins afterstart

    number of characters.

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

    $strin* = 'nd no% for so&ethin* co&letely different';

    $needle = 'thin*';

    echo stros($strin*9 $needle);

    1L

    $7

  • 8/12/2019 Php for Files

    68/176

    Mario Lurig

    See Also:

    strrpos() -Finds the last occurrence ofneedleinhaystack

    stripos() -Finds the first occurrence ofneedleinhaystack,case insensitive

    . . .

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

    $strin* = 'hello';

    $needle = 'h';

    if (stros($strin*9$needle) == P8S+){ // e"alatin* e>ality echo '

  • 8/12/2019 Php for Files

    69/176

    strpos() -Finds the first occurrence ofneedleinhaystack

    strripos() -Finds the last occurrence ofneedleinhaystack,case insensitive

    stripos(haystack, needle [, start])

    haystack-$string

    needle-$string

    start- [optional]$integer

    Returns the position (number of characters from the beginning ofhaystack)of the firstoccurrence ofneedleinhaystack,case insensitive. Ifstartis included, searching begins

    afterstartnumber of characters.

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

    $strin* = 'nd no% for so&ethin* co&letely different';

    $needle = '

  • 8/12/2019 Php for Files

    70/176

    strrpos() -Finds the last occurrence ofneedleinhaystack,case sensitivestripos() -

    Finds the first occurrence ofneedleinhaystack,case insensitive

    strstr(haystack, needle)

    haystack-$string

    needle-$string

    Find ifneedleis found inhaystackand returns the first occurrence ofneedleto the end

    ofhaystack.

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

    $strin* = '%%%Fexa&leFco&';

    $needle = 'exa&le';

    echo strstr($strin*9 $needle);

    exa&leFco&

    See Also:

    stristr() -case insensitive version ofstrstr()

    stristr(haystack, needle)

    haystack-$string

    needle-$string

    Finds ifneedleis found inhaystackand returns the first occurrence ofneedleto

    the end ofhaystack,case insensitive.

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

    Example:

    $strin* = '%%%Fexa&leFco&';

    $needle = '+TEQ8+';

    echo stristr($strin*9 $needle) ;

    exa&leFco&

    See Also:

    strstr() -case sensitive version ofstristr()

    strlen($string)

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

    http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com'
  • 8/12/2019 Php for Files

    71/176

    Mario Lurig

    $strin* = 'Hello!'; echo

    strlen($strin*);

    strtolower($string)

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

    Example:

    $strin* = 'Eario 8ri*';echo strtolo%er($strin*);

    &ario lri*

    strtoupper($string)

    Converts all characters in$stringto uppercase and returns the new string.Example:

    $strin* = 'Eario 8ri*';echo strtoer($strin*);

    E: 8:G

    ucfirst($string)Converts the first character in$stringto uppercase and returns the new string.

    Example:

    $strin* = 'i %ish i had so&e caitaliVation'; echocfirst($strin*);

    %ish i had so&e caitaliVation

    ucwords($string)

    Converts the first alphabetic characters of words in$stringto uppercase and returns

    the new string.

    Example:$strin* = 'i %ish i had Athree so&e caitaliVation'; echo

    c%ords($strin*);

    Wish Had Athree So&e aitaliVation

    71

    Example:

  • 8/12/2019 Php for Files

    72/176

    Mario Lurig

    strpbrk(haystack,characters)

    haystack-$string

    characters-$string

    Find if any of the characters inneedleare found inhaystackand returns the first

    occurrence of the character found inneedleto the end ofhaystack.Note:If needle is not

    found in haystack, FALSE is returned.

    Example:

    $strin* = '%%%Fexa&leFco&/indexFht&';

    $needle = 'F/c';echo strr($strin*9 $needle); // Pinds the eriod (F) firstFexa&leFco&/indexFht&

    See Also:

    strstr()- Same asstrpbrk()but searches for a string instead of characters

    strrev($string)

    Reverses a string.

    Example:

    echo strre"('hello %orld');

    dlro% olleh

    72

    http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com%2Findex.htm'http://var/www/apps/conversion/tmp/scratch_1/http:%2F%2F'www.example.com%2Findex.htm'
  • 8/12/2019 Php for Files

    73/176

    PHP Reference: Beginner to Intermediate PHP5

  • 8/12/2019 Php for Files

    74/176

    Mario Lurig

    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. Withoutforeach,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 (preformatted) tag for easier readability if an array contains more thanone 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(); // 3efine $array asFFF an array

    $array = array( '"ale'9 't%o'9 'three' ); // ndexed array

    $array = array( 'ey' = '"ale'9 'Ro' = 'slacer' ); // ssociati"e

    $array = array();

    $array,. = '"ale'; // ssi*n value to next a"ailale indexed ey $array,-. =

    '"ale'; // ssi*n value to the ey of - $array,'na&e'. = '"ale'; // ssi*n

    value to the ey name

    // ssi*n the "ale of ey - in $array to $"ale $"ale =

    $array,-.;

    // ssi*n the "ale of the ey name in $array to $"ale $"ale= $array,'na&e'.;

    74

  • 8/12/2019 Php for Files

    75/176

    PHP Reference: Beginner to Intermediate PHP5

    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$arrayto lowercase(default)or

    uppercase.

    Examples:

    $array = array( '

  • 8/12/2019 Php for Files

    76/176

    PHP Reference: Beginner to Intermediate PHP5

    (,Ro. = dad

    )

    array_combine(key_array,value_array)

    key_array-$array

    value_array-$array

    Creates a new array using the values fromkey_arrayas the keys and the values from

    value_arrayas the values.

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

    $eys = array ( 'na&e'9 'Ro'9 'a*e' );

    $"ales = array ( 'Yo'9 'ni*ht'9

    ? );

    $ne%array = arrayDco&ine($eys9 $"ales);

    rintDr($ne%array);

    rray

    (,na&e. ( Yo,Ro. ( ni*ht,a*e. ( ?

    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$arraysupplied.

    Example:

    76

    $array = array ( A = 'one'9 - = 't%o'9 ? = 'three' );

    rintDr( arrayD&er*e($array) );

    rray

    ,-.= one,1.= t%o,?.= three

    )

  • 8/12/2019 Php for Files

    77/176

    PHP Reference: Beginner to Intermediate PHP5

    $array = array ( 'Vero'9 'one'9 'na&e' = 'Yo' );

    $array? = array ( 'alsoVero'9 'na&e' = 'ohn'9 'Ro' = 'far&er' );

    rintDr( arrayD&er*e($array9 $array?) );

    ( ,-. ( Vero

    ,1. = one

    ,na&e. ( ohn

    ,?. ( alsoVero

    ,Ro. ( far&er)

    See Also:

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

    . . .

    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 ( 'Vero'9 'na&e' = 'Yo'9 'Ro' = 'layer' ); $array?

    = array ( 'alsoVero'9 'Ro' = 'far&er' );

    rintDr( $array @ $array? );

    rray

    (,-. ( Vero,na&e. ( Yo,Ro. (layer

    )

    ___________________________________________________________________________

    array_count_values($array)

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

    values.

    Note:Does not work for multi-dimensional arrays.

    Example:

    $array = array ( 'Vero'9 'one'9 'Vero' );rintDr( arrayDcontD"ales($array) );

    rray

    (

    ,Vero. ( ?,one. ( 1)

    See Also:

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

    77

  • 8/12/2019 Php for Files

    78/176

    PHP Reference: Beginner to Intermediate PHP5

    count($array [,mode])

    mode- [optional]$integerdefault:0, does not count multidimensional arrays Othervalue: 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 unlessmodeis set to 1.

    Examples:

    $array = array ('Vero'9

    'na&es' = array ( 'Rohn'9 'cla"e' )9

    'a*es' = array ( ??9 A ) );

    echo cont($array);

    A

    echo cont($array9 1);

    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 infirst_arrayand returns an

    array with the entries offirst_arraywhich do not share values with entries in$array(s).

    Example:$array = array( 'one'9 't%o'9 'three'9 'for' );

    $array? = array( 't%o'9 'three' ); $arrayA = array(

    'o' = 'one' );

    // "ale is 'one'9 &atchin* $array

    rintDr( arrayDdiff($array9 $array?9 $arrayA) );

    rray ( ,A. = for )

    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)

    78

  • 8/12/2019 Php for Files

    79/176

    PHP Reference: Beginner to Intermediate PHP5

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

    Accepts multiple$arrayfor comparison against first_array

    first_array-$array

    Compares the keys of all$array(s) against the keys infirst_arrayand returns an array

    with the entries offirst_arraywhich do not share keys with entries in$array(s).

    Example:

    $array = $array? =

    rintDr(

    rray ( ,na&e. = Rohn )

    See Also:

    array_diff()- Same comparison, but based on values onlyarray_diff_assoc()- Same

    comparison, but based on both keys and values

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

    Accepts multiple$arrayfor comparison against first_array first_array-

    $array

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

    returns an array with the entries offirst_arraywhich do not share exact keys andvalues with entries in$array(s).

    Example:

    $array = array( 'Vero'9 'one'9 'na&e' = 'Rohn' ); $array?

    = array( 'Vero'9 'alsoone'9 'na&e' = 'Rohn' );

    rintDr( arrayDdiffDassoc($array9 $array?) );

    rray ( ,1. = one )

    See Also:

    array_diff_key()- Same comparison, but based on keys instead of valuesarray_diff()-

    Same comparison, but based on values only

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

    Accepts multiple$arrayfor comparison against first_array first_array-

    $array

    Compares the values of all$array(s) against the values infirst_arrayand returns an

    array with the entries offirst_arraywhich share values with entries from all$array(s).

    79

    array( 'Vero'9 'na&e' = 'Rohn'9 'Ro' = 'Rohn' );array( 'alsoVero'9 'Ro' = 'Rohn' );

    arrayDdiffDey($array9 $array?));

  • 8/12/2019 Php for Files

    80/176

    Example:

    $array = array( 'one'9 't%o');

    $array? = array( 't%o'9 'one'9 'three'9 'for' ); // 'oneyy

    19't%o' &atch

    $arrayA = array( 'o' = 'one' );

    // only 'one' &atches rintDr( arrayDintersect($array9

    $array?9 $arrayA) );

    rray ( ,-. = one )

    See Also:

    array_intersect_key() -Same comparison, but based on keysarray_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.