Tuesday, 27 June 2017

PHP Questions and Answers.

 

PHP 7 Features :
1. Zend Engine:  PHP 7 is using zend engine 3.0. We call it as PHPNG.

   It is increase the performance of the application.

2. Return Type: Able to declare a return type for their function.

   In  PHP 7 where you will be able to declare what type of value will be returned.

 Eg. :

   public function area (float $r) : float

    {

       return 3.14*$r*$r;

    }

3.Spaceship Operator:
     
The new operator spaceship operator introduced in php 7

Ex :  PHP with <7
function sort ($a,$b)

    {   if ($a>$b)

            return 1;

        else if ( $a ==$b)

            return 0;

       else            return -1;

    }

PHP >7

function sort ($a,$b)

    {

       return $a < = > $b;

    }

 4. Null Coalesce Operator:

  The coalesce operator (??) returns result of its first operand if it exists, or null if it doesn’t.

Eg. :

PHP<7:

  if (isset ($_GET [‘name’]))

   {

        $name = $_GET [‘name’];

   }

   else

        $name = null;

In PHP>7:

$name = $_GET [‘name’]?? Null;

 5.Unicode Codepoint Escape Syntax : PHP 7 introduced syntax to escape

Unicode codepoint as below :

         echo “\u{202E} Reverse “;   // This outputs : esreveR

6.Deprecation of mysql_* functions: PHP 7 has deprecated all mysql_* functions, now developers have to use mysqli (the intelligent version of MySQL) instead.

7.
Constant Arrays Using define():

         In PHP 7, you can also define the array as a constant by using define.

     Example:

                define('NAME', array('Chandar','Ram','Gugu'));

                echo NAME[1]; // outputs "Chandar"

8.Group use declarations:
         Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.
   Example:     // Pre PHP 7 code
                use some\namespace\ClassA;
                use some\namespace\ClassB;
                use some\namespace\ClassC as C;
                // PHP 7+ code
                use some\namespace\{ClassA, ClassB, ClassC as C};
9.Integer division with intdiv():
                The new intdiv() function performs an integer division of its operands and returns it.
                Example:

                var_dump(intdiv(10, 3));

                The above example will output: int(3)

Cons:
If anyone has functions like “ereg” and “mysql” buried deep inside their code base, they are gonna strike a Backward Compatibility wall as these functions are deprecated and, it is going to be a real pain in the behind to upgrade.

Interview Questions :

http://codeigniterhelp.blogspot.in/p/interview-questions100.html

  
1. What is the output of the following code:
      
$a = '1';
      $b = &$a;
      $b = "2$b";
    echo $a.", ".$b;

      ANS : 21, 21


2.What is the use of header() function in php ?

ANS: The header() function sends a raw HTTP header to a client browser. Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

3.what is sql injection ?

ANS : SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

4.What is the difference between explode() and split() functions?

ANS : Split function splits string into array by regular expression. Explode splits a string into array by string.

5.How do I escape data before storing it into the database?  

  ANS :   addslashes function enables us to escape data before storage into the database.

          $str "Is your name O'Reilly?";

          // Outputs: Is your name O\'Reilly?
          echo addslashes($str);

         -------------------------------------------------------------------------

         $string="O'Reilly";

         $ser=serialize($string);    # safe -- won't count the slash

         echo $ser;

         echo " <br/>".$result=addslashes($ser);

 6.How is it possible to remove escape characters from a string?

 ANS : The stripslashes function enables us to remove the escape characters before apostrophes in a string.

7.Is it possible to remove the HTML tags from data?

ANS : The strip_tags() function enables us to clean a string from the HTML tags.

8.What does accessing a class via :: means?

ANS :      '::' is used to access static methods that do not require object initialization.

9.In PHP, objects are they passed by value or by reference?

ANS : In PHP, objects passed by value.

10.Are Parent constructors called implicitly inside a class constructor?

ANS: No, a parent constructor have to be called explicitly as follows:

parent::constructor($value)

11.What is faster?

ANS: 1- Combining two variables as follows:

$variable1 = ‘Hello ‘;

$variable2 = ‘World’;

$variable3 = $variable1.$variable2;

Or

2- $variable3 = “$variable1$variable2”;

$variable3 will contain “Hello World”. The first code is faster than the second code especially for large large sets of data.

12.How Many Types of Cookies in php ?
 

  There are 2 types of cookies: (1) Session Based which expire at the end of the session.

(2) Persistent cookies which are written on harddisk.

    Session cookies expire at the end of the session. This means,

when you close your browser window, the session cookie is deleted. This

website only uses session cookies.

 Persistent cookies do not expire at the end of the session.

A session cookie may be created when you visit a site or portion of a site. The cookie exists

for the duration of your visit. For example, a session cookie is created when you use the

Personal Login to access secured pages. Depending on the settings in your browser, you

may have the option to deny the session cookie; however, if you deny the cookie you may

have trouble using the site which relies on that cookie.

 

PHP provided setcookie() function to set a cookie. This function requires upto six arguments

and should be called before <html>

tag. For each cookie this function has to be called separately.

 setcookie(name, value, expire, path<optional>, domain<optional>, security <optional>);

 <?php

   setcookie("name", "John Watkin", time()+3600, "/","", 0);

   setcookie("age", "36", time()+3600, "/", "",  0);

?>

 

Here is the detail of all the arguments:

 

·         Name - This sets the name of the cookie and is stored in

·         an environment variable called HTTP_COOKIE_VARS. This variable is used

·         while accessing cookies.

 

·         Value -This sets the value of the named variable and is the content that you actually

·         want to store.

 

·         Expiry -  This specify a future time in seconds since

·         00:00:00 GMT on 1st Jan 1970. After this time cookie will become

·         inaccessible. If this parameter is not set then cookie will

·         automatically expire when the Web Browser is closed.

 

·         Path -This specifies the directories for which the cookie

·         is valid. A single forward slash character permits the cookie to be

·         valid for all directories.

 

·         Domain - This can be used to specify the domain name in

·         very large domains and must contain at least two periods to be valid.

·         All cookies are only valid for the host and domain which created them.

 

·         Security -  This can be set to 1 to specify that the

·         cookie should only be sent by secure transmission using HTTPS otherwise

·         set to 0 which mean cookie can be sent by regular HTTP.

 

  13.When sessions ends?

ANS: Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().

14.What is the difference between session_unregister() and session_unset()?

ANS: The session_unregister() function unregister a global variable from the current session and the session_unset() function free all session variables.

15.What does $GLOBALS means?

ANS: $GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
EX :
  
$a 1; $b 2;
function 
Sum()
{
    
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];

Sum();
echo 
$b;

16.what is the difference between $_ENV,$_SESSION and $_COOKIE?
 ANS : 
All three are superglobal, that means any script in your application can access it, BUT while $_SESSION and $_COOKIE are different (and private) for each user, the $_ENV super global is not specific to a user. The difference between $_SESSION and $_COOKIE is that $_ENV can live beyond the current user visit, while the session will end when the user leave your site (or close his browser). $_ENV contains environment variables, mainly containing information about your server, paths, etc

17.what is htaccess? why do we use this and where ?

 ANS :  htaccess files are configuration files of Apache Server that provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular

18.What is the difference between "echo" and "print" in PHP?

ANS : Echo can output one or more string but print can only output one string and always returns 1.

Echo is faster than print because it does not return any value


19
.PHP Data Types?

ANS: PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types:

1.      Scalar Types

2.      Compound Types

3.      Special Types 

PHP Data Types: Scalar Types

There are 4 scalar data types in PHP.

1.      boolean

2.      integer

3.      float

4.      string

     PHP Data Types: Compound Types

      There are 2 compound data types in PHP.     

1.      array

2.      object

      PHP Data Types: Special Types

     There are 2 special data types in PHP.

1.      resource

2.      NULL

20.How many types of array are there in PHP?

     There are three types of array in PHP:

·        Indexed array

·        Associative array

·        Multidimensional array

21.Difference between array_merge and array_combine in php? 

 ANS :  $array1 = array('one','two');    $array2 = array(1,2);    

     $result=array_merge($array1,$array2);
       print_r($result);

         Array ( [0] => one [1] => two [2] => 1 [3] => 2 )

     $result  = array_combine($array1,$array2);
      print_r($result);

       Array ( [one] => 1 [two] => 2 ) 

 

22.What is array_search() in php?

   ANS : array_search — Searches the array for a given value and returns the first corresponding key if successful.
$key = array_search('green', $array); // $key = 2; 

23.What is substr() in php ?

$rest substr("abcdef"0, -1);  // returns "abcde"

$rest substr("abcdef"2, -1);  // returns "cde"

$rest substr("abcdef"4, -4);  // returns false

 

$rest substr("abcdef", -3, -1); // returns "de"

echo substr('abcdef'1);     // bcdef

echo substr('abcdef'13);  // bcd

echo substr('abcdef'04);  // abcd

echo substr('abcdef'08);  // abcdef

echo substr('abcdef', -11); // f

24. What is a Session ?

ANS : A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

23.
 Cookies Vs. Sessions :

·        Cookies are small files that are stored in the visitor's browser.

·        Cookies can have a long lifespan, lasting months or even years.

·        Cookies are limited in size depending on each browser's default settings.

·        Cookies can be disabled if the visitor's browser does not allow them (uncommon).

·        Cookies can be edited by the visitor. (Do not use cookies to store sensitive data.)

Sessions :

·        Sessions are small files that are stored on the website's server.

·        Sessions have a limited lifespan; they expire when the browser is closed.

·        Sessions are only limited in size if you limit their size on the server.

·        Sessions cannot be disabled by the visitor because they are not stored in the browser.

·        Sessions cannot be edited by the visitor.

  session.save_path = "c:/wamp/tmp" in server system

 

23. What is faster?
1- Combining two variables as follows:
      $variable1 = ‘Hello ‘;
      $variable2 = ‘World’;  $variable3 = $variable1.$variable2;

(Or)

2- $variable3 = “$variable1$variable2”;

 ANS:  :      
  $variable3 will contain “Hello World”. The first code is faster than the second code     especially for large large sets of data.


24.What is the difference between session_unregister() and session_unset()?ANS : The session_unregister() function unregister a global variable from the current session and the session_unset() function free all session variables.

25.Difference between mysql_connect and mysql_pconnect?

ANS: There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the database new connection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

26. What is ob_start() in php?

ANS: The PHP output buffering will save all the server outputs ( html and php prints) to a string variable. So to start buffering, use ob_start(); this will keep saved any output. Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

27.Heredoc vs Nowdoc in PHP

ANS :
1.Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.
2. Parsing is done inside is done in  Heredoc but while coming to nowdoc  no parsing is done inside.
3. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.
ex: $foo = 'bar';
$here = <<<HERE

    I'm here, $foo!

HERE;

$now = <<<'NOW'

    I'm now, $foo!

NOW;

Ans : $here is "I'm here, bar!", while $now is "I'm now, $foo!".

 28. How to print  string in PHP ?

ANS :  

PHP strings can be specified not just in two ways, but in four ways.

PHP strings can be specified not just in two ways, but in four ways.

1.    Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed). 

2.    Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you what to echo "The $types are" That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.

3.    Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.

4.    Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'No parsing is done in nowdoc.

29. Any five array functions .

   array_change_key_case($age,CASE_UPPER)
      The array_change_key_case() function changes all keys in an array to lowercase or uppercase.
array_column() -- Returns the values from a single column in the input array
array_count_values() -- Count all the values of an array
ex : $a=array("A","Cat","Dog","A","Dog");

print_r(array_count_values($a));
out put -- 
Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )
array_combine()   -- Creates an array by using the elements from one "keys" array and one "values" array array_diff()  -- Compare arrays, and returns the differences (compare values only)
array_search()  -- Searches an array for a given value and returns the keyarray_unique()  -- Removes duplicate values from an array
array_values() -- Returns all the values of an array
array_walk()  --  Applies a user function to every member of an array
array_walk_recursive()  --  Applies a user function recursively to every member of an array (multi dimensional array)  

30. What is __set() and __get() methods in PHP?           

ANS : 
  By default PHP is a Loosely typed language and therefore it is not necessary to declare variables before using them. This also holds true for using class members. Look at an example below.

<?php

class Customer {
public $name;
}

$c = new Customer();
$c->name = “Sunil”; // $name is set because its public

$c->email = “email@domain.com”; //assigning email@domain.com to the $email variable.

?>

Ideally in a strict language this would have been an error. But, with PHP this works perfectly well as you can assign values to an undefined variable.

Because of the above limitation, PHP engine provides two magic methods __get() and __set()__get() is used when value from an undefined variable is to be read and __set() is used when a value is to be assigned to a undefined variable of a class
__set() allows you to provide functionality to validate data being stored. See example below

<?php
class Customer {

public $name;
private $data = array();

public function __set($dt, $vl) {
$this->data[$dt] = $vl;
}

public function __get($dt) {
return $this->data[$dt];
}
}

$c = new Customer();
$c->name = “Sunil”; // $name is set because its public

$c->email = “email@domain.com”; //assigning email@domain.com to the $email variable.

echo $c->email;

?>

  Ref: http://www.sunilb.com/php/php5-oops-tutorial-__get-and-__set

31. What is default session name in php ?

ANS : PHPSESSID
 EXP:  session_start();
echo "<b>Session name using get:</b>", session_name();

32. What is output for below program.?
 
$a=5;
echo "<br/>";
echo $a;
echo "<br/>";
echo $a+++$a++;
echo "<br/>";
echo $a;
echo "<br/>";
echo $a---$a--;
echo "<br/>";
echo $a;   

ANS :   

5
11
7
1
5


32. Write program for String Reverse with out using string functions?
Ans:
$string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
      $reverse = $string[$i].$reverse;
      $i++;
}
echo $reverse;

//outputnahseez


--------------------------------------Qualcom-----------------------  

difference library an helper in codeigniter

diff cookie and session what happens when cookie disables in browser

what procedure how the performance increase when use procedure reason

what is the first file load in codeigniter

what is the purpose of route file

what is the scope resolution operator

what is static and what is dynamic

how to set session in codeigniter

how to pass dynamic value to url in codeigniter

difference between :num and :any

what is trigger ?

trigger syntax?

difference between method overloading and method overriding

Does php supports method oveloading? why?

what is compile time error and what is runtime error?     
-----------------------------------knowledge -------------------------------------------
folder1

     -folder12

          -folder121

              -folder1212

folder2

      -folder21

         -folder211

             -folder2112

 

1.design databse for above tree stucture it is n-th series like more and more folders

 2. what is the query to get second heighest salary?

 3. Difference between abstract class and interface?

 4. $text = "helllo";

    $text['10'] = 'abs';

what is the length of string from above code?

 5. Design Database Registration form for all input elements.

-----------------------------------------------------------------------------------------------------------
Different types of array functions in php
What is array_walk,array_map
environment variables in php
namespace in php
how to get first 50 records in mysql
how to get current date in mysql
how to get form now to one month records
how to get mapped records from two tables with left join.
Normal forms in mysql
Views in mysql
Functions ,stored procedures
Each in JQuery
Diff in $input and input
What are elements in jquery