Php Interview Questions With Answers

  • Uploaded by: Abhishek Kumar Singh
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Php Interview Questions With Answers as PDF for free.

More details

  • Words: 24,207
  • Pages: 102
What Are the Special Characters You Need to Escape in Single-Quoted Stings? There are two special characters you need to escape in a single-quote string: the single quote (') and the back slash (\). Here is a PHP script example of single-quoted strings:

This script will print: Hello world!It's Friday!\ represents an operator.

Can You Specify the "new line" Character in Single-Quoted Strings? You can not specify the "new line" character in a single-quoted string. If you don't believe, try this script:

This script will print: \n will not work in single quoted strings.

How Many Escape Sequences Are Recognized in Single-Quoted Strings? There are 2 escape sequences you can use in single-quoted strings: • •

\\ - Represents the back slash character. \' - Represents the single quote character.

What Are the Special Characters You Need to Escape in Double-Quoted Stings? There are two special characters you need to escape in a double-quote string: the double quote (") and the back slash (\). Here is a PHP script example of double-quoted strings:

This script will print:

Hello world!Tom said: "Who's there?"\ represents an operator.

How Many Escape Sequences Are Recognized in Double-Quoted Strings? There are 12 escape sequences you can use in double-quoted strings: • • • • • • • • • • • •

\\ - Represents the back slash character. \" - Represents the double quote character. \$ - Represents the dollar sign. \n - Represents the new line character (ASCII code 10). \r - Represents the carriage return character (ASCII code 13). \t - Represents the tab character (ASCII code 9). \{ - Represents the open brace character. \} - Represents the close brace character. \[ - Represents the open bracket character. \] - Represents the close bracket character. \nnn - Represents a character as an octal value. \xnn - Represents a character as a hex value.

How To Include Variables in Double-Quoted Strings? Variables included in double-quoted strings will be interpolated. Their values will be concatenated into the enclosing strings. For example, two statements in the following PHP script will print out the same string:

This script will print: part 1 and part 2 part 1 and part 2

How Many Ways to Include Variables in Double-Quoted Strings? There are 3 formats to include variables in double-quoted strings: •



"part 1 $variable part 2" - This is the simplest format to include a variable in a string. The variable name starts with the dollar sign and ends at the first character that can not be used in variable name. Space is good character to end a variable name. "part 1${variable}part 2" - This format helps you to clearly end the variable name. The variable name starts at dollar sign before the open brace (${) and ends at the close brace (}).



"part 1{$variable}part 2" - This format is also called complex format. You use this format to specify any complex variable expression in the same way as in a normal statement. The variable expression starts at ({$) followed by a variable name and ends at (}).

Here is a PHP script example of different ways to include variables in double-quoted strings:

This script will print: Heineken's taste is great. He drank some Heinekens and water. She drank some Heinekens and water.

How Many Ways to Include Array Elements in Double-Quoted Strings? There are 2 formats to include array elements in double-quoted strings: • •

"part 1 $array[key] part 2" - This is called simple format. In this format, you can not specify the element key in quotes. "part 1 {$array['key']} part 2" - This is called complex format. In this format, the array element expression is specified in the same way as in a normal statement.

Here is a PHP script example of different ways to include variables in double-quoted strings: 'red', 'banana' => 'yellow'); echo "A banana is $fruits[banana].\n"; echo "A banana is {$fruits['banana']}.\n"; ?>

This script will print: A banana is yellow. A banana is yellow.

"A banana is $fruits['banana'].\n" will give you a syntax error. How To Access a Specific Character in a String? Any character in a string can be accessed by a special string element expression:



$string{index} - The index is the position of the character counted from left and starting from 0.

Here is a PHP script example:

This script will print: The first character is It's Friday!{0} The first character is I

How To Assigning a New Character in a String? The string element expression, $string{index}, can also be used at the left side of an assignment statement. This allows you to assign a new character to any position in a string. Here is a PHP script example:

This script will print: It's Friday? It's Friday!

How to Concatenate Two Strings Together? You can use the string concatenation operator (.) to join two strings into one. Here is a PHP script example of string concatenation:

This script will print: Hello world!

How To Compare Two Strings with Comparison Operators?

PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. Those operators use ASCII values of characters from both strings to determine the comparison results. Here is a PHP script on how to use comparison operators: $b) { print('$a > $b is true.'."\n"); } else { print('$a > $b is false.'."\n"); } if ($a == $b) { print('$a == $b is true.'."\n"); } else { print('$a == $b is false.'."\n"); } if ($a < $b) { print('$a < $b is true.'."\n"); } else { print('$a < $b is false.'."\n"); } ?>

This script will print: $a > $b is true. $a == $b is false. $a < $b is false.

How To Convert Numbers to Strings? In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:

This script will print: -1300 5 Price = $99.99 3

. "\n"); " . 1+2 . "\n"); " . (1+2) . "\n"); 3\n");

1 + 2 = 3 1 + 2 = 3

The print() function requires a string, so numeric value -1.3e3 is automatically converted to a string "-1300". The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1 . " + " . 2 . " = " . 1+2 . "\n") is a little bit interesting. The result is "3\n" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached, we have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1. How To Convert Strings to Numbers? In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules: • •

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.

Here is a PHP script example of converting some examples:

This script will print: $foo=11.5; type is double $foo=-1299; type is double $foo=1; type is integer $foo=1; type is integer $foo=11; type is integer $foo=14.2; type is double $foo=11; type is double

($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n";

$foo=11; type is double

How To Get the Number of Characters in a String? You can use the "strlen()" function to get the number of characters in a string. Here is a PHP script example of strlen():

This script will print: 12

How To Remove White Spaces from the Beginning and/or the End of a String? There are 4 PHP functions you can use remove white space characters from the beginning and/or the end of a string: • • • •

trim() - Remove white space characters from the beginning and the end of a string. ltrim() - Remove white space characters from the beginning of a string. rtrim() - Remove white space characters from the end of a string. chop() - Same as rtrim().

White space characters are defined as: • • • • • •

" " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NULL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Here is a PHP script example of trimming strings:

This script will print:

leftTrimmed = (Hello world! rightTrimmed = ( bothTrimmed = (Hello world!)

) Hello world!)

How To Remove the New Line Character from the End of a Text Line? If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:

How To Remove Leading and Trailing Spaces from User Input Values? If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:

How to Find a Substring from a Given String? To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():

This script will print: pos1 = (13); type is integer pos2 = (0); type is integer pos3 = (); type is boolean

"pos3" shows strpos() can return a Boolean value. What Is the Best Way to Test the strpos() Return Value? Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate "0" and "false". Check out this PHP script on how to use strpos():

This script will print: Not found based (==) test Found based (===) test

Of course, (===) test is correct. How To Take a Substring from a Given String? If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():

This script will print: Position counted from left: begin

Position counted form right: gin

substr() can take negative starting position counted from the end of the string. How To Replace a Substring in a Given String? If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():

This script will print: Warning: System will shutdown in 15 minutes! (10 minutes later) Warning: System will shutdown in 5 minutes!

Like substr(), substr_replace() can take negative starting position counted from the end of the string. How To Reformat a Paragraph of Text? You can wordwrap() reformat a paragraph of text by wrapping lines with a fixed length. Here is a PHP script on how to use wordwrap():

This script will print: TRADING ON MARGIN POSES ADDITIONAL RISKS AND IS NOT SUITABLE FOR ALL INVESTORS. A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT.

The result is not really good because of the extra space characters. You need to learn preg_replace() to replace them with a single space character. How To Convert Strings to Upper or Lower Cases? Converting strings to upper or lower cases are easy. Just use strtoupper() or strtolower() functions. Here is a PHP script on how to use them:

This script will print: php string functions are easy to use. PHP STRING FUNCTIONS ARE EASY TO USE.

How To Convert the First Character to Upper Case? If you are processing an article, you may want to capitalize the first character of a sentence by using the ucfirst() function. You may also want to capitalize the first character of every words for the article title by using the ucwords() function. Here is a PHP script on how to use ucfirst() and ucwords():

This script will print: Php string functions are easy to use. Php String Functions Are Easy To Use.

How To Compare Two Strings with strcmp()? PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. But if you want to get an integer result by comparing two strings, you can the strcmp() function, which compares two strings based on ASCII values of their characters. Here is a PHP script on how to use strcmp():



This script will print: strcmp($a, $b): 1 strcmp($b, $a): -1 strcmp($a, $a): 0

As you can see, strcmp() returns 3 possible values: • • •

1: The first string is greater than the section string. -1: The first string is less than the section string. 0: The first string is equal to the section string.

How To Convert Strings in Hex Format? If you want convert a string into hex format, you can use the bin2hex() function. Here is a PHP script on how to use bin2hex():

This script will print: Hello

world!

48656c6c6f09776f726c64210a

How To Generate a Character from an ASCII Value? If you want to generate characters from ASCII values, you can use the chr() function. chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr():

This script will print:

Hello 72

How To Convert a Character to an ASCII Value? If you want to convert characters to ASCII values, you can use the ord() function, which takes the first charcter of the specified string, and returns its ASCII value in decimal format. ord() complements chr(). Here is a PHP script on how to use ord():

This script will print: 72 H

How To Split a String into Pieces? There are two functions you can use to split a string into pieces: • •

explode(substring, string) - Splitting a string based on a substring. Faster than split(). split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():

This script will print: explode() returns: Array ( [0] => php [1] => strting [2] => function.html )

split() Array ( [0] [1] [2] [3] )

returns: => => => =>

php strting function html

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".". How To Join Multiple Strings into a Single String? If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():

This script will print: A formated date: 01/01/2006 A keyword list: php, string, function

How To Apply UUEncode to a String? UUEncode (Unix-to-Unix Encoding) is a simple algorithm to convert a string of any characters into a string of printable characters. UUEncode is reversible. The reverse algorithm is called UUDecode. PHP offeres two functions for you to UUEncode or UUDecode a string: convert_uuencode() and convert_uudecode(), Here is a PHP script on how to use them: $msgEncoded<--\n"); print("UUDecoded message:\n"); print("-->$msgDecoded<--\n"); } else {

print("Conversion not OK:\n");

} ?>

This script will print: Conversion OK UUEncoded message: -->M1G)O;0E4;PE3=6)J96-T#0I*;V4)3&5E"4AE;&QO#0I$86X)2VEA"4=R965T #:6YG ` <-UUDecoded message: --> From To Subject Joe Lee Hello Dan Kia Greeting<--

The output shows you that the UUEncode string is a multiple-line string with a special end-of-string mark \x20. How To Replace a Group of Characters by Another Group? While processing a string, you may want to replace a group of special characters with some other characters. For example, if you don't want to show user's email addresses in the original format to stop email spammer collecting real email addresses, you can replace the "@" and "." with something else. PHP offers the strtr() function with two format to help you: • •

strtr(string, from, to) - Replacing each character in "from" with the corresponding character in "to". strtr(string, map) - Replacing each substring in "map" with the corresponding substring in "map".

Here is a PHP script on how to use strtr(): " at ", "." => " dot "); print("Original: $email\n"); print("Character replacement: ".strtr($email, "@.", "#_")."\n"); print("Substring replacement: ".strtr($email, $map)."\n"); ?>

This script will print: Original: [email protected] Character replacement: joe#dev_pickzycenter_moc Substring replacement: joe at dev dot pickzycenter dot moc

To help you to remember the function name, strtr(), "tr" stands for "translation".

What Is an Array in PHP? An array in PHP is really an ordered map of pairs of keys and values. Comparing with Perl, an array in PHP is not like a normal array in Perl. An array in PHP is like an associate array in Perl. But an array in PHP can work like a normal array in Perl. Comparing with Java, an array in PHP is not like an array in Java. An array in PHP is like a TreeMap class in Java. But an array in PHP can work like an array in Java. How To Create an Array? You can create an array using the array() constructor. When calling array(), you can also initialize the array with pairs of keys and values. Here is a PHP script on how to use array(): "PHP", "One"=>"Perl", "Two"=>"Java"); print_r($mappedArray); print("\n"); ?>

This script will print: Empty array: Array ( ) Array with Array ( [0] => [1] => [2] => )

default keys: PHP Perl Java

Array with specified keys: Array (

)

[Zero] => PHP [One] => Perl [Two] => Java

How To Test If a Variable Is an Array? Testing if a variable is an array is easy. Just use the is_array() function. Here is a PHP script on how to use is_array():

This script will print: Test Test Test Test Test Test

1: 1 2: 1 3: 4: 5: 6:

How To Retrieve Values out of an Array? You can retrieve values out of arrays using the array element expression $array[$key]. Here is a PHP example script: This script will print: Array with default keys: The second value: Perl Array with specified keys: The third value: Java

What Types of Data Can Be Used as Array Keys? Two types of data can be used as array keys: string and integer. When a string is used as a key and the string represent an integer, PHP will convert the string into a integer and use it as the key. Here is a PHP script on different types of keys:

This script will print: Array with mixed keys: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic ) $mixed[3] = C+ $mixed["3"] = C+ $mixed[""] = Basic

Note that an empty string can also be used as a key. How Values in Arrays Are Indexed? Values in an array are all indexed their corresponding keys. Because we can use either an integer or a string as a key in an array, we can divide arrays into 3 categories: • • •

Numerical Array - All keys are sequential integers. Associative Array - All keys are strings. Mixed Array - Some keys are integers, some keys are strings.

Can You Add Values to an Array without a Key? Can You Add Values to an Array with a Key? The answer is yes and no. The answer is yes, because you can add values without specipickzyng any keys. The answer is no,

because PHP will add a default integer key for you if you are not specipickzyng a key. PHP follows these rules to assign you the default keys: • •

Assign 0 as the default key, if there is no integer key exists in the array. Assign the highest integer key plus 1 as the default key, if there are integer keys exist in the array.

Here is a PHP example script:

This script will print: Array with default keys: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN )

Can You Copy an Array? You can create a new array by copying an existing array using the assignment statement. Note that the new array is not a reference to the old array. If you want a reference variable pointing to the old array, you can use the reference operator "&". Here is a PHP script on how to copy an array: "PHP", "One"=>"Perl", "Two"=>"Java"); $newArray = $oldArray; $refArray = &$oldArray; $newArray["One"] = "Python"; $refArray["Two"] = "C#"; print("\$newArray[\"One\"] = ".$newArray["One"]."\n"); print("\$oldArray[\"One\"] = ".$oldArray["One"]."\n"); print("\$refArray[\"Two\"] = ".$refArray["Two"]."\n");

print("\$oldArray[\"Two\"] = ".$oldArray["Two"]."\n"); ?>

This script will print: $newArray["One"] $oldArray["One"] $refArray["Two"] $oldArray["Two"]

= = = =

Python Perl C# C#

How to Loop through an Array? The best way to loop through an array is to use the "foreach" statement. There are two forms of "foreach" statements: • •

foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array. foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.

Here is a PHP script on how to use "foreach" on an array: "PHP", "One"=>"Perl", "Two"=>"Java"); $array["3"] = "C+"; $array[""] = "Basic"; $array[] = "Pascal"; $array[] = "FORTRAN"; print("Loop on value only:\n"); foreach ($array as $value) { print("$value, "); } print("\n\n"); print("Loop on key and value:\n"); foreach ($array as $key=>$value) { print("[$key] => $value\n"); } ?>

This script will print: Loop on value only: PHP, Perl, Java, C+, Basic, Pascal, FORTRAN, Loop on key and value: [Zero] => PHP [One] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN

How the Values Are Ordered in an Array? PHP says that an array is an ordered map. But how the values are ordered in an array? The answer is simple. Values are stored in the same order as they are inserted like a queue. If you want to reorder them differently, you need to use a sort function. Here is a PHP script show you the order of array values:

This script will print: Order of array values: Array ( [Two] => [3] => C+ [Zero] => PHP [1] => Perl [] => Basic [5] => FORTRAN )

How To Copy Array Values to a List of Variables? If you want copy all values of an array to a list of variable, you can use the list() construct on the left side of an assignment operator. list() will only take values with integer keys starting from 0. Here is a PHP script on how to use list() construct: "PHP", 1=>"Basic", "One"=>"Perl", 0=>"Pascal", 2=>"FORTRAN", "Two"=>"Java"); list($first, $second, $third) = $array; print("Test 3: The third language = $third\n"); ?>

This script will print: Test 1: The third site = Netscape Test 2: Year = 2006 Test 3: The third language = FORTRAN

Test 2 uses the array returned by the split() function. Test 3 shows that list() will ignore any values with string keys. How To Get the Total Number of Values in an Array? You can get the total number of values in an array by using the count() function. Here is a PHP example script:

This script will print: Size 1: 3 Size 2: 0

Note that count() has an alias called sizeof(). How Do You If a Key Is Defined in an Array? There are two functions can be used to test if a key is defined in an array or not: • •

array_key_exists($key, $array) - Returns true if the $key is defined in $array. isset($array[$key]) - Returns true if the $key is defined in $array.

Here is a PHP example script: "PHP", "One"=>"Perl", "Two"=>"Java"); print("Is 'One' defined? ".array_key_exists("One", $array)."\n"); print("Is '1' defined? ".array_key_exists("1", $array)."\n"); print("Is 'Two' defined? ".isset($array["Two"])."\n"); print("Is '2' defined? ".isset($array[2])."\n"); ?>

This script will print: Is 'One' defined? 1 Is '1' defined? Is 'Two' defined? 1

Is '2' defined?

How To Find a Specific Value in an Array? There are two functions can be used to test if a value is defined in an array or not: • •

array_search($value, $array) - Returns the first key of the matching value in the array, if found. Otherwise, it returns false. in_array($value, $array) - Returns true if the $value is defined in $array.

Here is a PHP script on how to use arrary_search():

This script will print: Search 1: 1 Search 2: 0 Search 3:

How To Get All the Keys Out of an Array? Function array_keys() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_keys():

This script will print: Keys of the input array: Array ( [0] => Zero

[1] [2] [3] [4] [5] [6]

=> => => => => =>

1 Two 3 4 5

)

How To Get All the Values Out of an Array? F unction array_values() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_values():

This script will print: Values of the input array: Array ( [0] => PHP [1] => Perl [2] => Java [3] => C+ [4] => Basic [5] => Pascal [6] => FORTRAN )

How To Sort an Array by Keys? Sorting an array by keys can be done by using the ksort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the keys. Here is a PHP script on how to use ksort():
$mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; ksort($mixed); print("Sorted by keys:\n"); print_r($mixed); ?>

This script will print: Sorted by keys: Array ( [] => Basic [Two] => Java [Zero] => PHP [1] => Perl [3] => C+ [4] => Pascal [5] => FORTRAN )

How To Sort an Array by Values? Sorting an array by values is doable by using the sort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the values. Then it will replace all keys with integer keys sequentially starting with 0. So using sort() on arrays with integer keys (traditional index based array) is safe. It is un-safe to use sort() on arrays with string keys (maps). Be careful. Here is a PHP script on how to use sort():

This script will print: Sorted by values: Array ( [0] => Basic [1] => C+

)

[2] [3] [4] [5] [6]

=> => => => =>

FORTRAN Java PHP Pascal Perl

How To Join a List of Keys with a List of Values into an Array? If you have a list keys and a list of values stored separately in two arrays, you can join them into a single array using the array_combine() function. It will make the values of the first array to be the keys of the resulting array, and the values of the second array to be the values of the resulting array. Here is a PHP script on how to use array_combine():

This script will print: Combined: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN ) Combined backward: Array ( [PHP] => Zero [Perl] => 1

[Java] => Two [C+] => 3 [Basic] => [Pascal] => 4 [FORTRAN] => 5

)

How To Merge Values of Two Arrays into a Single Array? You can use the array_merge() function to merge two arrays into a single array. array_merge() appends all pairs of keys and values of the second array to the end of the first array. Here is a PHP script on how to use array_merge(): "Windows", "ii"=>"Unix", "iii"=>"Mac"); $mixed = array_merge($lang, $os); print("Merged:\n"); print_r($mixed); ?>

This script will print: Merged: Array ( [0] => Perl [1] => PHP [2] => Java [i] => Windows [ii] => Unix [iii] => Mac )

How To Use an Array as a Queue? A queue is a simple data structure that manages data elements following the first-in-firstout rule. You use the following two functions together to use an array as a queue: • •

array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value. array_shift($array) - Remove the first value from the array and returns it. All integer keys will be reset sequentially starting from 0.

Here is a PHP script on how to use an array as a queue:
$next = array_shift($waitingList); array_push($waitingList, "Kia"); $next = array_shift($waitingList); array_push($waitingList, "Sam"); print("Current waiting list:\n"); print_r($waitingList); ?>

This script will print: Current Array ( [0] [1] [2] )

waiting list: => Kim => Kia => Sam

How To Use an Array as a Stack? A stack is a simple data structure that manages data elements following the first-in-lastout rule. You use the following two functions together to use an array as a stack: • •

array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value. array_pop($array) - Remove the last value from the array and returns it.

Here is a PHP script on how to use an array as a queue:

This script will print: Current Array ( [0] [1] [2] )

waiting list: => Jeo => Leo => Sam

How To Randomly Retrieve a Value from an Array? If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:

This script will print: Random greeting: Coucou!

How To Loop through an Array without Using "foreach"? PHP offers the following functions to allow you loop through an array without using the "foreach" statement: • • • • • • •

reset($array) - Moves the array internal pointer to the first value of the array and returns that value. end($array) - Moves the array internal pointer to the last value in the array and returns that value. next($array) - Moves the array internal pointer to the next value in the array and returns that value. prev($array) - Moves the array internal pointer to the previous value in the array and returns that value. current($array) - Returns the value pointed by the array internal pointer. key($array) - Returns the key pointed by the array internal pointer. each($array) - Returns the key and the value pointed by the array internal pointer as an array and moves the pointer to the next value.

Here is a PHP script on how to loop through an array without using "foreach": "PHP", "One"=>"Perl", "Two"=>"Java"); print("Loop with each():\n"); reset($array); while (list($key, $value) = each($array)) { print("[$key] => $value\n"); } print("\n"); print("Loop with current():\n"); reset($array); while ($value = current($array)) { print("$value\n"); next($array);

} print("\n"); ?>

This script will print: Loop with each(): [Zero] => PHP [One] => Perl [Two] => Java Loop with current(): PHP Perl Java

How To Create an Array with a Sequence of Integers or Characters? The quickest way to create an array with a sequence of integers or characters is to use the range() function. It returns an array with values starting with the first integer or character, and ending with the second integer or character. Here is a PHP script on how to use range():

This script will print: Integers: Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => )

1 4 7 10 13 16 19

Characters: Array ( [0] => X

)

[1] => Y [2] => Z [3] => [ [4] => \ [5] => ] [6] => ^ [7] => _ [8] => ` [9] => a [10] => b [11] => c

Of course, you can create an array with a sequence of integers or characters using a loop. But range() is much easier and quicker to use. How To Pad an Array with the Same Value Multiple Times? If you want to add the same value multiple times to the end or beginning of an array, you can use the array_pad($array, $new_size, $value) function. If the second argument, $new_size, is positive, it will pad to the end of the array. If negative, it will pad to the beginning of the array. If the absolute value of $new_size if not greater than the current size of the array, no padding takes place. Here is a PHP script on how to use array_pad(): "PHP", "One"=>"Perl", "Two"=>"Java"); $array = array_pad($array, 6, ">>"); $array = array_pad($array, -8, "---"); print("Padded:\n"); print(join(",", array_values($array))); print("\n"); ?>

This script will print: Padded: ---,---,PHP,Perl,Java,>>,>>,>>

How To Truncate an Array? If you want to remove a chunk of values from an array, you can use the array_splice($array, $offset, $length) function. $offset defines the starting position of the chunk to be removed. If $offset is positive, it is counted from the beginning of the array. If negative, it is counted from the end of the array. array_splice() also returns the removed chunk of values. Here is a PHP script on how to use array_splice(): "PHP", "One"=>"Perl", "Two"=>"Java"); $removed = array_splice($array, -2, 2); print("Remaining chunk:\n"); print_r($array);

print("\n"); print("Removed chunk:\n"); print_r($removed); ?>

This script will print: Remaining chunk: Array ( [Zero] => PHP ) Removed chunk: Array ( [One] => Perl [Two] => Java )

How To Join Multiple Strings Stored in an Array into a Single String? If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():

This script will print: A formated date: 01/01/2006 A keyword list: php, string, function

How To Split a String into an Array of Substring? There are two functions you can use to split a string into an Array of Substring: • •

explode(substring, string) - Splitting a string based on a substring. Faster than split(). split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():



This script will print: explode() returns: Array ( [0] => php [1] => strting [2] => function.html ) split() returns: Array ( [0] => php [1] => strting [2] => function [3] => html )

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".". How To Get the Minimum or Maximum Value of an Array? If you want to get the minimum or maximum value of an array, you can use the min() or max() function. Here is a PHP script on how to use min() and max(): "PHP", "One"=>"Perl", "Two"=>"Java"); print("Minimum string: ".min($array)."\n"); print("Maximum string: ".max($array)."\n"); ?>

This script will print: Minimum Maximum Minimum Maximum

number: number: string: string:

1 7 Java Perl

As you can see, min() and max() work for string values too.

How To Define a User Function? You can define a user function anywhere in a PHP script using the function statement like this: "function name() {...}". Here is a PHP script example on how to define a user function:

This script will print: Hello world!

How To Invoke a User Function? You can invoke a function by entering the function name followed by a pair of parentheses. If needed, function arguments can be specified as a list of expressions enclosed in parentheses. Here is a PHP script example on how to invoke a user function:

This script will print: Hello Bob!

How To Return a Value Back to the Function Caller? You can return a value to the function caller by using the "return $value" statement. Execution control will be transferred to the caller immediately after the return statement. If there are other statements in the function after the return statement, they will not be executed. Here is a PHP script example on how to return values:

This script will print:

This year is: 2006

How To Pass an Argument to a Function? To pass an argument to a function, you need to: • •

Add an argument definition in the function definition. Add a value as an argument when invoking the function.

Here is a PHP script on how to use arguments in a function():

This script will print: Celsius: 37.777777777778 Celsius: -40

How Variables Are Passed Through Arguments? Like more of other programming languages, variables are passed through arguments by values, not by references. That means when a variable is passed as an argument, a copy of the value will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing variables by values:

This script will print: Before swapping: PHP, JSP After swapping: PHP, JSP

As you can see, original variables were not affected.

How To Pass Variables By References? You can pass a variable by reference to a function by taking the reference of the original variable, and passing that reference as the calling argument. Here is a PHP script on how to use pass variables by references:

This script will print: Before swapping: PHP, JSP After swapping: JSP, PHP

As you can see, the function modified the original variable. Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details. Can You Define an Argument as a Reference Type? You can define an argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an argument as a reference type:

This script will print: Before swapping: PHP, JSP

After swapping: JSP, PHP

Can You Pass an Array into a Function? You can pass an array into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:

This script will print: Average: 3.75

How Arrays Are Passed Through Arguments? Like a normal variable, an array is passed through an argument by value, not by reference. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:

This script will print: Before shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5,7,6,2,1,3,4,2

As you can see, original variables were not affected. How To Pass Arrays By References? Like normal variables, you can pass an array by reference into a function by taking a reference of the original array, and passing the reference to the function. Here is a PHP script on how to pass array as reference:



This script will print: Before shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5

Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details. Can You Define an Array Argument as a Reference Type? You can define an array argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:

This script will print: BBefore shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5

How To Return an Array from a Function? You can return an array variable like a normal variable using the return statement. No special syntax needed. Here is a PHP script on how to return an array from a function:
?>

This script will print: Lucky numbers: 35,24,15,7,26,15

If you like those nummers, take them to buy a PowerBall ticket. What Is the Scope of a Variable Defined in a Function? The scope of a local variable defined in a function is limited with that function. Once the function is ended, its local variables are also removed. So you can not access any local variable outside its defining function. Here is a PHP script on the scope of local variables in a function: function myPassword() { $password = "U8FIE8W0"; print("Defined inside the function? ". isset($password)."\n"); } myPassword(); print("Defined outside the function? ". isset($password)."\n"); ?>

This script will print: Defined inside the function? 1 Defined outside the function?

What Is the Scope of a Variable Defined outside a Function? A variable defined outside any functions in main script body is called global variable. However, a global variable is not really accessible globally any in the script. The scope of global variable is limited to all statements outside any functions. So you can not access any global variables inside a function. Here is a PHP script on the scope of global variables: $login = "pickzycenter"; function myLogin() { print("Defined inside the function? ". isset($login)."\n"); } myLogin(); print("Defined outside the function? ". isset($login)."\n"); ?>

This script will print:

Defined inside the function? Defined outside the function? 1

How To Access a Global Variable inside a Function? By default, global variables are not accessible inside a function. However, you can make them accessible by declare them as "global" inside a function. Here is a PHP script on declaring "global" variables: $intRate = 5.5; function myAccount() { global $intRate; print("Defined inside the function? ". isset($intRate)."\n"); } myAccount(); print("Defined outside the function? ". isset($intRate)."\n"); ?>

This script will print: Defined inside the function? 1 Defined outside the function? 1

How Values Are Returned from Functions? If a value is returned from a function, it is returned by value, not by reference. That means that a copy of the value is return. Here is a PHP script on how values are returned from a function:

This script will print: Favorite tool: vbulletin Favorite tool: vbulletin

As you can see, changing the value in $favor does not affect $myFavor. This proves that the function returns a new copy of $favor.

How To Return a Reference from a Function? To return a reference from a function, you need to: • •

Add the reference operator "&" when defining the function. Add the reference operator "&" when invoking the function.

Here is a PHP script on how to return a reference from a function:

This script will print: Favorite tool: vbulletin Favorite tool: phpbb

As you can see, changing the value in $favor does affect $myFavor, because $myFavor is a reference to $favor. How To Specify Argument Default Values? If you want to allow the caller to skip an argument when calling a function, you can define the argument with a default value when defining the function. Adding a default value to an argument can be done like this "function name($arg=expression){}. Here is a PHP script on how to specify default values to arguments:

This script will print: PHP download PHP hosting

How To Define a Function with Any Number of Arguments? If you want to define a function with any number of arguments, you need to: Declare the function with no argument. Call func_num_args() in the function to get the number of the arguments. Call func_get_args() in the function to get all the arguments in an array.

• • •

Here is a PHP script on how to handle any number of arguments:

This script will print: Average 1: 109.33333333333 Average 2: 107.66666666667

How To Read a Text File into an Array? If you have a text file with multiple lines, and you want to read those lines into an array, you can use the file() function. It opens the specified file, reads all the lines, puts each line as a value in an array, and returns the array to you. Here is a PHP script example on how to use file():

This script will print: # This file contains port numbers for well-known services echo ftp telnet

7/tcp 21/tcp 23/tcp

smtp ...

25/tcp

Note that file() breaks lines right after the new line character "\n". Each line will contain the "\n" at the end. This is why we suggested to use rtrime() to remove "\n". Also note that, if you are on Unix system, your Internet service file is located at "/etc/services". How To Read the Entire File into a Single String? If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():

This script will print: Size of the file: 7116

How To Open a File for Reading? If you want to open a file and read its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the specified file, and returns a file handle. The second argument "r" tells PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:

This script will print: Type of file handle: resource The first line from the file handle: # Copyright (c) 1993-1999

Note that you should always call fclose() to close the opened file when you are done with the file. How To Open a File for Writing?

If you want to open a new file and write date to the file, you can use the fopen($fileName, "w") function. It creates the specified file, and returns a file handle. The second argument "w" tells PHP to open the file for writing. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for writing:

This script will write the following to the file: Download PHP scripts at dev.pickzycenter.com.

Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you should use "\n". How To Append New Data to the End of a File? If you have an existing file, and want to write more data to the end of the file, you can use the fopen($fileName, "a") function. It opens the specified file, moves the file pointer to the end of the file, and returns a file handle. The second argument "a" tells PHP to open the file for appending. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for appending:

This script will write the following to the file: Remote host: 64.233.179.104. Query string: cate=102&order=down〈=en.

As you can see, file cgi.log opened twice by the script. The first call of fopen() actually created the file. The second call of fopen() opened the file to allow new data to append to the end of the file. How To Read One Line of Text from a File?

If you have a text file with multiple lines, and you want to read those lines one line at a time, you can use the fgets() function. It reads the current line up to the "\n" character, moves the file pointer to the next line, and returns the text line as a string. The returning string includes the "\n" at the end. Here is a PHP script example on how to use fgets():

This script will print: # This file contains port numbers for well-known services echo ftp telnet smtp ...

7/tcp 21/tcp 23/tcp 25/tcp

Note that rtrim() is used to remove "\n" from the returning string of fgets(). How To Read One Character from a File? If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():

This script will print: Number of /: 113

Note that rtrim() is used to remove "\n" from the returning string of fgets(). What's Wrong with "while ($c=fgetc($f)) {}"?

If you are using "while ($c=fgetc($f)) {}" to loop through each character in a file, the loop may end in the middle of the file when there is a "0" character, because PHP treats "0" as Boolean false. To properly loop to the end of the file, you should use "while ( ($c=fgetc($f)) !== false ) {}". Here is a PHP script example on incorrect testing of fgetc():

This script will print: Remote host: 64.233.179.1

As you can see the loop indeed stopped at character "0". How To Read a File in Binary Mode? If you have a file that stores binary data, like an executable program or picture file, you need to read the file in binary mode to ensure that none of the data gets modified during the reading process. You need to: • •

Open the file with fopen($fileName, "rb"). Read data with fread($fileHandle,$length).

Here is a PHP script example on reading binary file:

This script will print:

About 16448 bytes read.

This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable. Try it: \temp\myping dev.pickzycenter.com. How To Write a String to a File with a File Handle? If you have a file handle linked to a file opened for writing, and you want to write a string to the file, you can use the fwrite() function. It will write the string to the file where the file pointer is located, and moves the file pointer to the end of the string. Here is a PHP script example on how to use fwrite():

This script will write the following to the file: Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Write a String to a File without a File Handle? If you have a string, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():

This script will print: Number of bytes written: 89

If you look at the file todo.txt, it will contain: Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Write an Array to a File without a File Handle?

If you have an array, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes all values from the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():

This script will print: Number of bytes written: 89

If you look at the file todo.txt, it will contain: Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Read Data from Keyborad (Standard Input)? If you want to read data from the standard input, usually the keyboard, you can use the fopen("php://stdin") function. It creates a special file handle linking to the standard input, and returns the file handle. Once the standard input is opened to a file handle, you can use fgets() to read one line at a time from the standard input like a regular file. Remember fgets() also includes "\n" at the end of the returning string. Here is a PHP script example on how to read from standard input:

This script will print: What's your name? Leo Hello Leo !

"!" is showing on the next line, because $name includes "\n" returned by fgets(). You can use rtrim() to remove "\n". If you are using your script in a Web page, there is no standard input.

If you don't want to open the standard input as a file handle yourself, you can use the constant STDIN predefined by PHP as the file handle for standard input. How To Open Standard Output as a File Handle? If you want to open the standard output as a file handle yourself, you can use the fopen("php://stdout") function. It creates a special file handle linking to the standard output, and returns the file handle. Once the standard output is opened to a file handle, you can use fwrite() to write data to the starndard output like a regular file. Here is a PHP script example on how to write to standard output:

This script will print: What's your name? To do: Looking for PHP hosting provider!

If you don't want to open the standard output as a file handle yourself, you can use the constant STDOUT predefined by PHP as the file handle for standard output. If you are using your script in a Web page, standard output is merged into the Web page HTML document. print() and echo() also writes to standard output. How To Create a Directory? You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():

This script will print: Directory created.

If you run this script again, it will print: Directory already exists.

How To Remove an Empty Directory? If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():

This script will print: Directory removed.

If you run this script again, it will print: Directory does not exist.

How To Remove a File? If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():

This script will print: File removed.

If you run this script again, it will print: File does not exist.

How To Copy a File?

If you have a file and want to make a copy to create a new file, you can use the copy() function. Here is a PHP script example on how to use copy():

This script will print: A copy of ping.exe is created.

How To Dump the Contents of a Directory into an Array? If you want to get the contents of a directory into an array, you can use the scandir() function. It gets a list of all the files and sub directories of the specified directory and returns the list as an array. The returning list also includes two specify entries: (.) and (..). Here is a PHP script example on how to use scandir():

This script will print: Array ( [0] => . [1] => .. [2] => todo.txt )

How To Read a Directory One Entry at a Time? If you want to read a directory one entry at a time, you can use opendir() to open the specified directory to create a directory handle, then use readdir() to read the directory contents through the directory handle one entry at a time. readdir() returns the current entry located by the directory pointer and moves the pointer to the next entry. When end of directory is reached, readdir() returns Boolean false. Here is a PHP script example on how to use opendir() and readdir():
$array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n"; $array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n"; $bytes = file_put_contents("/temp/download/todo.txt", $array); print("List of files:\n"); $dir = opendir("/temp/download"); while ( ($file=readdir($dir)) !== false ) { print("$file\n"); } closedir($dir); ?>

This script will print: List of files: . .. todo.txt

How To Get the Directory Name out of a File Path Name? If you have the full path name of a file, and want to get the directory name portion of the path name, you can use the dirname() function. It breaks the full path name at the last directory path delimiter (/) or (\), and returns the first portion as the directory name. Here is a PHP script example on how to use dirname():

This script will print: File full path name: /temp/download/todo.txt File directory name: /temp/download

How To Break a File Path Name into Parts? If you have a file name, and want to get different parts of the file name, you can use the pathinfo() function. It breaks the file name into 3 parts: directory name, file base name and file extension; and returns them in an array. Here is a PHP script example on how to use pathinfo():

This script will print: Array ( [dirname] => /temp/download [basename] => todo.txt [extension] => txt )

How To Create a Web Form? If you take input data from visitors on your Web site, you can create a Web form with input fields to allow visitors to fill in data and submit the data to your server for processing. A Web form can be created with the
tag with some input tags. The &FORM tag should be written in the following format: ......


Where "processing.php" specifies the PHP page that processes the submitted data in the form. What Are Form Input HTML Tags? HTML tags that can be used in a form to collect input data are: • • • • • •

<SUBMIT ...> - Displayed as a button allow users to submit the form. - Displayed as an input field to take an input string. - Displayed as a radio button to take an input flag. - Displayed as a checkbox button to take an input flag. <SELECT ...> - Displayed as a dropdown list to take input selection.