Top Courses in IT & Software 728x90

Friday 12 February 2016

Best PHP interview questions part 3



PHP-interview-questions-answers
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?
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():
<?php 
$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."\n");
print("Search 2: ".array_search("Perl",$array)."\n");
print("Search 3: ".array_search("C#",$array)."\n");
print("\n");
?>
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():
<?php 
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$keys = array_keys($mixed);
print("Keys of the input array:\n");
print_r($keys);
?>
This script will print:
Keys of the input array:
Array
(
    [0] => Zero
    [1] => 1
    [2] => Two
    [3] => 3
    [4] =>
    [5] => 4
    [6] => 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():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$values = array_values($mixed);
print("Values of the input array:\n");
print_r($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():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$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():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
sort($mixed);
print("Sorted by values:\n");
print_r($mixed);
?>
This script will print:
Sorted by values:
Array
(
    [0] => Basic
    [1] => C+
    [2] => FORTRAN
    [3] => Java
    [4] => PHP
    [5] => Pascal
    [6] => Perl

)

0 comments:

Post a Comment

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