Top 20 job interveiw questions on php

Posted by Unknown at 00:57




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(): <?php
$haystack = "needle234953413434516504381640386488129";
$pos = strpos($haystack, "needle");
if ($pos==false) {
print("Not found based (==) test\n");
} else {
print("Found based (==) test\n");
}
if ($pos===false) {
print("Not found based (===) test\n");
} else {
print("Found based (===) test\n");
}
?>


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(): <?php
$string = "beginning";
print("Position counted from left: ".substr($string,0,5)."\n");
print("Position counted form right: ".substr($string,-7,3)."\n");
?>


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(): <?php
$string = "Warning: System will shutdown in NN minutes!";
$pos = strpos($string, "NN");
print(substr_replace($string, "15", $pos, 2)."\n");
sleep(10*60);
print(substr_replace($string, "5", $pos, 2)."\n");
?>


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(): <?php
$string = "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.";
$string = str_replace("\n", " ", $string);
$string = str_replace("\r", " ", $string);
print(wordwrap($string, 40)."\n");
?>


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: <?php
$string = "PHP string functions are easy to use.";
$lower = strtolower($string);
$upper = strtoupper($string);
print("$lower\n");
print("$upper\n");
print("\n");
?>


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(): <?php
$string = "php string functions are easy to use.";
$sentence = ucfirst($string);
$title = ucwords($string);
print("$sentence\n");
print("$title\n");
print("\n");
?>


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(): <?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
print('strcmp($a, $b): '.strcmp($a, $b)."\n");
print('strcmp($b, $a): '.strcmp($b, $a)."\n");
print('strcmp($a, $a): '.strcmp($a, $a)."\n");
?>


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(): <?php
$string = "Hello\tworld!\n";
print($string."\n");
print(bin2hex($string)."\n");
?>


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(): <?php 
print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n");
print(ord("H")."\n");
?>


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(): <?php 
print(ord("Hello")."\n");
print(chr(72)."\n");
?>


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(): <?php 
$list = explode("_","php_strting_function.html");
print("explode() returns:\n");
print_r($list);
$list = split("[_.]","php_strting_function.html");
print("split() returns:\n");
print_r($list);
?>


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 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(): <?php 
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date: ".implode("/",$date)."\n");
print("A keyword list: ".implode(", ",$keys)."\n");
?>


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: <?php
$msgRaw = "
From\tTo\tSubject
Joe\tLee\tHello
Dan\tKia\tGreeting";
$msgEncoded = convert_uuencode($msgRaw);
$msgDecoded = convert_uudecode($msgEncoded);
if ($msgRaw === $msgDecoded) {
print("Conversion OK\n");
print("UUEncoded message:\n");
print("-->$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(): <?php
$email = "joe@dev.pickzycenter.moc";
$map = array("@" => " at ", "." => " dot ");
print("Original: $email\n");
print("Character replacement: ".strtr($email, "@.", "#_")."\n");
print("Substring replacement: ".strtr($email, $map)."\n");
?>


This script will print: Original: joe@dev.pickzycenter.moc
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 
print("Empty array:\n");
$emptyArray = array();
print_r($emptyArray);
print("\n");

print("Array with default keys:\n");
$indexedArray = array("PHP", "Perl", "Java");
print_r($indexedArray);
print("\n");

print("Array with specified keys:\n");
$mappedArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print_r($mappedArray);
print("\n");
?>


This script will print: Empty array:
Array
(
)

Array with default keys:
Array
(
[0] => PHP
[1] => Perl
[2] => 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(): <?php 
$var = array(0,0,7);
print("Test 1: ". is_array($var)."\n");
$var = array();
print("Test 2: ". is_array($var)."\n");
$var = 1800;
print("Test 3: ". is_array($var)."\n");
$var = true;
print("Test 4: ". is_array($var)."\n");
$var = null;
print("Test 5: ". is_array($var)."\n");
$var = "PHP";
print("Test 6: ". is_array($var)."\n");
print("\n");
?>


This script will print: Test 1: 1
Test 2: 1
Test 3:
Test 4:
Test 5:
Test 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: 

<?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"] = "Perl"; $languages["Two"] = "Java"; print("Array with inserted values:\n"); print_r($languages); ?> 

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: <?php 
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
print("Array with mixed keys:\n");
print_r($mixed);
print("\$mixed[3] = ".$mixed[3]."\n");
print("\$mixed[\"3\"] = ".$mixed["3"]."\n");
print("\$mixed[\"\"] = ".$mixed[""]."\n");
?>


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: <?php 
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
print("Array with default keys:\n");
print_r($mixed);
?>


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 
$oldArray = array("Zero"=>"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"] = Python
$oldArray["One"] = Perl
$refArray["Two"] = C#
$oldArray["Two"] = 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 
$array = array("Zero"=>"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: <?php 
$mixed = array();
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$mixed["Two"] = "";
unset($mixed[4]); 
print("Order of array values:\n");
print_r($mixed);
?>


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
$array = array("Google", "Yahoo", "Netscape");
list($first, $second, $third) = $array;
print("Test 1: The third site = $third\n");
list($month, $date, $year) = split("/","1/1/2006");
print("Test 2: Year = $year\n");
$array = array("Zero"=>"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: <?php 
$array = array("PHP", "Perl", "Java");
print_r("Size 1: ".count($array)."\n");
$array = array();
print_r("Size 2: ".count($array)."\n");
?>


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 
$array = array("Zero"=>"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?



click the Below link download this file 


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

Blog Archive

 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top