1. What do you mean by array? Explain with example various ways to define array in PHP?
2. Explain with example: foreach loop for arrays and while loop for arrays.
3. List and explain various array operators.
4. Explain with example: Multi dimensional array.

A multidimensional array is an array containing one or more arrays.

PHP understands multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element

PHP – Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array





array(“Land Rover”,17,15)


5. Explain with example following functions for array:

i. sort ii. Asort iii. Ksort  iv. Rsort v. arsort vi. Krsort vii. Shuffle viii. Array_reverse           ix. Array_push  x. array_pop xi. Each xii. Current xiii. Reset xiv. End xv. Next xvi. Pos  xvii. Prev xvii. Array_walk  xviii. Count xix. Sizeof xx. Array_count_values xxi. Extract

$transport = array(‘foot’, ‘bike’,’bike’, ‘car’, ‘plane’);
$mode = current($transport);         // $mode = ‘foot’; –>current mode(pointer is on)=foot
echo count($transport);      //counts the number of elements in an array
echo “<br>”;
print_r(array_count_values($transport));  //counts all the values of an array
echo “<br>current mode is :$mode<br>”;

// Get the current position
echo pos($transport);
echo “<br>”;

$mode1 = end($transport);
echo “end mode is: $mode1<br>”;

$mode2 = prev($transport);
echo “previous to last mode is:$mode2<br>”;
if ($mode2==FALSE)
echo “false”;
};            //foot

//reset — Set the internal pointer of an array to its first element
echo “value after reset is :”;
echo current($transport) . “<br />”;

//The each() function returns the current element key and value, and moves the internal pointer forward.
$krina=”myname”;//assigned value for extract function
$name = array(“krina” => “joshi”, “kkk” => “jjj”,”lll”=>”mmm”);
$names = each($name);
echo “<br>size of array is:”;
echo sizeof($name);

//array_walk — Apply a user function to every member of an array, Returns TRUE on success or FALSE on failure.
function test($a)
echo “$a <Br>”;
echo “hello <Br>”;

extract($name, EXTR_PREFIX_SAME, “dup”);
echo “\$krina = $krina; \$kkk = $kkk; \$dup_krina=”;

echo $a;



6. Explain following string manipulation functions:

i. isset ii. Empty iii. Substr iv. Strops v. stripos vi. Strrpos vii. Strripos  viii. Str_replace  

xi. str_ireplace x. ltrim xi. Rtrim xii. Trim xiii. Str_pad xiv. Lcfirst xv. Ucfirst xvi. Ucword   

xvii. strtolower xviii. Strtoupper xix. Strrev xx. Str_shuffle xxi. Str_repeat xxii. Explode

xxiii. implode xxiv. Addslashes xxv. Stripslashes xxvi. Chr xxvii. Ord  xxviii. Strtok       xxix. strcmp   xxx. Strcasecmp xxxi. Strnatcasecmp xxxii. Strnatcmp xxxiii. Strlen       xxxiv. strstr   xxxv. Strchr xxxvi.  Strchr xxxvii. Strrchr xxxviii. Stristr xxxix. Str_replace

xxxx. substr_replace   

echo strtolower(“Krina Joshi.”);
echo “<br>”;

echo strtoupper(“Krina Joshi.”);
echo “<br>”;

//Convert the first character of “Krina” to lowercase:
echo lcfirst(“Krina Joshi.”);
echo “<br>”;
//Convert the first character of “krina” to uppercase:
echo ucfirst(“krina Joshi.”);
echo “<br>”;
//Convert the first character of each word to uppercase:
echo ucwords(“krina Joshi.”);
echo “<br>”;

echo strrev(“Krina Joshi.”);
echo “<br>”;

echo strlen(“Krina Joshi.”);
echo “<br>”;

echo str_shuffle(“Krina Joshi.”);
echo “<br>”;
$name = “krina,joshi,hi,hello”;
echo str_replace(“k”,”h”,”$name”);
echo “<br>”;
echo “explode: <br>”;
echo “<br>”;

$arr = array(‘Hello’,’krina!’,’Beautiful’,’Day!’);
echo implode(” “,$arr);
echo “<br>”;

//Pad to the right side of the string, to a new length of 20 characters:
echo str_pad(“krina”,20,”.”);

//Repeat the string 3 times:
echo str_repeat(“Krina Joshi.”,3);

echo “<br>”;

//The strnatcmp() function compares two strings using a “natural” algorithm.
//In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in “10” is less than 2.
echo “strnatcmp——->”;
echo strnatcmp(“2Hello krina!”,”10Hello krina!”);
echo “<br>”;
echo “strnatcmp——->”;
echo strnatcmp(“10Hello krina!”,”2Hello krina!”);
echo “<br>”;

//The strnatcasecmp() function compares two strings using a “natural” algorithm.

echo strnatcasecmp(“2Hello krina!”,”10Hello krina!”);
echo “<br>”;
echo strnatcasecmp(“10Hello krina!”,”2Hello krina!”);
echo “<br>”;

//Find the first occurrence of “krina” inside “Hello krina!” and return the rest of the string:
echo strchr(“Hello krina!”,”krina”);
echo “<br>”;

//Search a string for “krina”, and return all characters from this position to the end of the string:
echo strrchr(“Hello krina!”,”krina”);
echo “<br>”;

//Replace “Hello” with “krina”:
echo substr_replace(“Hello”,”krina”,0);

echo trim(”     :      krina Joshi “);
echo “<br>”;
echo ltrim(”       hello    :      krina Joshi “);

echo “<br>”;
echo rtrim(”                            krina Joshi                  :    xyz     “);

echo “<br>”;
echo substr(“krina Joshi”,6,5).”<BR>”;//joshi
echo substr(“krina Joshi”,-4).”<BR>”;//4 character from last
/* strcmp
•    0 – if the two strings are equal
•    <0 – if string1 is less than string2
•    >0 – if string1 is greater than string2
echo strcmp(“awelcome!”,”Awelcome!”) .”<BR>”;

echo strcasecmp(“Hello krina!”,”HELLO krina!”) . “<br>”;//str1 is equal to str2
echo strcasecmp(“Hello”,”hell”) . “<br>”;
echo strcasecmp(“krina joshi”,”k”) . “<br>”;//str1 is greater than str2 so o/p >0

echo strpos(“krina joshi”,”j”);
echo “<br>”;
echo strrpos(“krina joshi”,”i”); // i will be searched from last
echo “<br>”;

//The strstr() function searches for the first occurrence of a string inside another string.
echo strstr(“Hello krina!”,”krina”);


7. What do you understand  by regular expression?What are the two main techniques for regular expression? 

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.

  • POSIX Regular Expressions
  • PERL Style Regular Expressions

    POSIX Regular Expressions:

    The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.
    The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.
    Lets give explaination for few concepts being used in POSIX regular expression. After that we will introduce you wih regular expression related functions.


    Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

    Expression Description
    [0-9] It matches any decimal digit from 0 through 9.
    [a-z] It matches any character from lowercase a through lowercase z.
    [A-Z] It matches any character from uppercase A through uppercase Z.
    [a-Z] It matches any character from lowercase a through uppercase Z.

    The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.


    The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each pecial character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.

    Expression Description
    p+ It matches any string containing at least one p.
    p* It matches any string containing zero or more p’s.
    p? It matches any string containing zero or more p’s. This is just an alternative way to use p*.
    p{N} It matches any string containing a sequence of N p’s
    p{2,3} It matches any string containing a sequence of two or three p’s.
    p{2, } It matches any string containing a sequence of at least two p’s.
    p$ It matches any string with p at the end of it.
    ^p It matches any string with p at the beginning of it.


    Following examples will clear your concepts about matching chracters.

    Expression Description
    [^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z.
    p.p It matches any string containing p, followed by any character, in turn followed by another p.
    ^.{2}$ It matches any string containing exactly two characters.
    <b>(.*)</b> It matches any string enclosed within <b> and </b>.
    p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.

    Predefined Character Ranges

    For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set:

    Expression Description
    [[:alpha:]] It matches any string containing alphabetic characters aA through zZ.
    [[:digit:]] It matches any string containing numerical digits 0 through 9.
    [[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
    [[:space:]] It matches any string containing a space.

    PHP’s Regexp POSIX Functions

    PHP currently offers seven functions for searching strings using POSIX-style regular expressions:

    Function Description
    ereg() The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
    ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
    eregi() The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
    eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
    split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
    spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
    sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.

    PERL Style Regular Expressions:

    Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.
    Lets give explaination for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions.


    A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.
    For instance, you can search for large money sums using the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.
    Following is the list of metacharacters which can be used in PERL Style Regular Expressions.

    Character Description . a single character \s a whitespace character (space, tab, newline) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified


    Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.

    Modifier Description i Makes the match case insensitive m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary o Evaluates the expression only once s Allows use of . to match a newline character x Allows you to use white space in the expression for clarity g Globally finds all matches cg Allows a search to continue even after a global match fails

    PHP’s Regexp PERL Compatible Functions

    PHP offers following functions for searching strings using Perl-compatible regular expressions:

    Function Description
    preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
    preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
    preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
    preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
    preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
    preg_ quote() Quote regular expression characters
8. Explain preg_match with its prototype and example.

  The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST[“name”]);

if (!preg_match(“/^[a-zA-Z ]*$/”,$name)) {

$nameErr = “Only letters and white space allowed”;


9. List with the meaning of POSIX character classes.

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

10. List with meaning of special characters used in POSIX regular expression outside square brackets.
11. List with meaning of special characters used in POSIX regular expression inside square brackets.
12. Explain subpattern with example.
Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

  1. It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of the words “cat”, “cataract”, or “caterpillar”. Without the parentheses, it would match “cataract”, “erpillar” or the empty string.
  2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.
13. What is the difference between require and include function?

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

Leave a Reply