Top Courses in IT & Software 728x90

Friday 12 February 2016

Best PHP Interview questions Part 2

PHP-interview-questions-answers


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

Click here for Part 3

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.