PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Friday, March 15, 2013

PHP - find biggest number in a array where array can also have nested arrays

PHP -Write a program to find biggest number in an array where array can also have nested arrays.

For example given an array like
Input : (1, 0, 6, 9, array(100, -1, 10, 7), 40, array(101, array(120, 240), 180), 200)

that can contain numbers and nested arrays containing numbers, we need to return the maximum number.

Output : 240


Program:


<?php

$inputArray = array(1, 0, 6, 9, array(100, -1, 10, 7), 40, array(101, array(120, 240), 180), 200);
echo findBiggest($inputArray);

function findBiggest($inputArray)
{
        static $biggest = 0;
        if(is_array($inputArray))
        {
                foreach($inputArray as $arr)
                {
                        findBiggest($arr);
                }
        }
        else
        {
                if($inputArray > $biggest)
                        $biggest = $inputArray;
        }
        return $biggest;

}

Wednesday, December 19, 2012

Avoid two users trying to access with same session cookie data?

How would you avoid two users trying to access with the same session cookie data?

This is same as asking how would you avoid Session Fixation or Session Hijacking.



Solution:
  1. Regenerate the Session Id on each user request i.e.  call session_regenerate_id() at the beginning of each request.
  2. Fix the active time of a session. If a user is logged in from time more than time out value, automatically log off the User.
  3. Check the 'browser fingerprint' on each request. This is a hash, stored in a $_SESSION variable, comprising some combination of the user-agent header, client IP address, a salt value, and/or other information. 
  4. Check referrer: this does not work for all systems, but if we know that users of this site must be coming from some known domain we can discard sessions tied to users from elsewhere.







Below is a sample code to implement this.


$timeout = 3 * 60; // 3 minutes
$fingerprint = md5('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT']);
session_start();
if ( (isset($_SESSION['last_active']) && (time() > ($_SESSION['last_active']+$timeout))) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint) || isset($_GET['logout']) ) 
{ 
         do_logout();
}
session_regenerate_id();
$_SESSION['last_active'] = time();
$_SESSION['fingerprint'] = $fingerprint;




Tuesday, November 6, 2012

difference between echo and print in PHP

Question : What is the difference between echo and print in PHP? Why do you use one over the other?


Solution: 

print and echo both are more or less the same. Both are used to display strings. 

They are not actually functions in php. They are language constructs. Benefit of language construct is that you dont have to put parantheses for the argument list.

Differences are
  • print has a return value of 1 so it can be used in expressions whereas echo returns void.
  • echo can take multiple parameters. 
  • echo is slightly faster than print.

Friday, July 6, 2012

Difference between innerHTML and appendChild

Jquery / Javascript : What is the difference between innerHTML and appendChild?


Answer :

  • appendChild is used to insert new node in DOM.
  • innerHTML is a property of DOM that allows to replace content of an element with different HTML, which automatically gets parsed into DOM nodes.

Monday, June 11, 2012

How does MVC pattern work?

How does MVC pattern work?


MVC ie Model View Controller pattern is a methodology for separating the business
logic (model) from the display logic (view) and the decisional controls (controller).


When a User clicks on a URL say http://php-geeks-wink.blogspot.in/ below are the steps processed
1. Front Controller receives the request and sets up the environment.
2. Thereon request reaches the controller.
3. Controller interacts with Model to perform any db queries.
4. Control then reaches to View, preparing the response.
5. Response is then sent back to the browser.

Tuesday, June 5, 2012

Difference between div and table


What is the difference between a div and table? When will you prefer one over the other?

1. Tables are quite acceptable for displaying layout elements that are in a tabular layout format. On the other hand, divs do not restrict the layout to tabular format. Instead, a div is like a “floating box” that can be positioned anywhere you want.

2. Divs helps seperating content from presentation.

3. Table make it more difficult for the search engine to find relevant information.

Wednesday, May 16, 2012

Default execution time?

What is the default execution time of a php script after which it gives fatal error?

Solution: it is 30s.


Next bullet fired--> How can you change it?

Solution: It can be configured via max_execution_time value defined in the php.ini
or
through set_time_limit(sec) function of php.



Tuesday, May 15, 2012

Long running queries in mysql

How would you cross check long running queries in mysql?


Solution: Two ways to do it...

1. Start mysqld with the --log-slow-queries[=file_name]

2. In my.cnf write
   log-slow-queries=file_name
 

Next question is what is the unit of time that we consider as threshold for measuring long running queries?
Answer is seconds and its default value is 10s

Its value can optionally be changed as
long_query_time=1

Monday, May 14, 2012

Girlfriend's Name?

Read the following piece of code


<form action="welcome.php" method="post">
             Your Name <input type="text" name="fname"/>
             Your Girl Friend Name: <input type="text" name="fname" />
             <input type="submit"/>
</form>




The php code of the welcome.php file is as follows:

Welcome <?php echo $_POST['fname'];?> and <?php echo $_POST['fname'];?>!




What will be the output if you give your name as Jim and your girlfriend's name as Nancy?
a) Welcome Jim and Nancy!
b) Welcome Jim and Jim!
c) Welcome Nancy and Jim!
d) Welcome Nancy and Nancy!



Solution is d) Welcome Nancy and Nancy!
surprising! isn't it, after having your girlfriend's name, php ignored you...:D

Sunday, May 13, 2012

PHP class as Database Wrapper

1. Design and code a PHP class that will act as wrapper to access database. Consider Security, Scalability, Maintenance etc while designing.

2. Use the class designed above to store, update and show the status message of a person on its wall at facebook.

Wednesday, May 9, 2012

Hotel Room Reservation System

This assignment is to develop a hotel room reservation system. We have 3 types of room(each with different pricing per day). Pricing per day will be appicable as per standard check-in/check-out time(which is 12pm) .

Below are the room types and per day prices

1. Single -            INR 1500
2. Double -          INR 2200
3. Luxury -          INR 3500

There are 100 rooms in hotel which are distributed as 50 single, 25 double and 25 luxury rooms.


You need to perform the following tasks:

1. Design a database for the reservation management(illustrate by a database/ER diagram).

2. Create a function using php to get all free rooms.
    Input : Check-in Date, No. of Days for stay
    Output : Available rooms, Price for entire stay.


3. Create a function to make reservation
    Input : Check-in Date, No of Days for stay
    Output : True/False - based on whether reservation was successfully made or not.


Wednesday, May 2, 2012

Mysql Sorting Order?

In What order will the output be sorted?

SELECT * FROM TABLE1 ORDER BY ID, NAME DESC;

a) sort descending on NAME then descending on ID
b) sort ascending on ID then descending on NAME
c) sort descending on NAME then ascending on ID
d) sort descending on ID and descending on NAME


Solution: b)

Friday, April 27, 2012

value of $result?

What is the value of $result in the following PHP cdoe?

<?php
function timesTwo($int)
{
$int = $int*2;
}
$int = 2;
$result = timesTwo($int);
?>


a) 2
b) 0
c) 4
d) Null


You need catchy eyes in order to answer this question correctly...
Solution is d) Null  :P

Sunday, April 1, 2012

Value of $a?

What is the value of $a?


<?php
$a=in_array('01',array('1'))==var_dump('01'==1);
?>


a) True
b) False
c) Syntax Error
d) Null


At first, answer seems to False because 01 being a string is not equal to 1. ryt?
But 01 here is an octal number and it equals the 1 that is decimal...
therefore answer is
a) True
any confusion?


Friday, March 30, 2012

Output of the below code?

What will be output of the below code?

<?php
$a=array(1,2,3);
$b=array(4,5,6);
$c=1;
$a[$c++]=$b[$c++];
print_r($a);
?>

a) Array(1,4,3)
b) Array(1,6,3)
c) Array(4,2,6)
d) Array(1,5,3)
e) Array(1,2,5)



Solution: b) Array(1,6,3)
Now take some time and think how we got this solution!

At first we assume that right side of = is calculated first and is then assigned to left side.
So $b[$c++] should return 5, by then $c would have reached to 2 so $a[2]=5;
and output should be Array(1,2,5)

But what actually happens is that left side of = is calculated first, and then the right B-)

Thursday, March 15, 2012

Output of the below code?

What will be the output of the below code?


<?php
$a=0;
echo empty($a),isset($a);
?>

a) 10
b) 11
c) Syntax Error
d) 0


Solution: b) 11
Please tell me how?

Friday, February 24, 2012

Output of the following code?

What will be the output of the below code?

<?php
$qpt = 'Eat to live, but not live to eat';
echo preg_match("/^to/",$qpt);
?>


a)1
b)2
c)0
d)Null


Solution: c)0

Wednesday, February 1, 2012

Delete the content without resetting the auto increment?

Which of the following command will delete the entire contents of a table without resetting the auto increment value?

a) drop table <tablename>
b) delete from <tablename>
c) truncate table <tablename>
d) remove table <tablename>



I think the answer should be
b) delete from <tablename>

because truncate resets the auto increment id value to 1.
Please share if your answer differs...

Thursday, January 19, 2012

Output of the following code?

What will be the output of the following code?

<?php
function changeme()
{
static $var=5;
return $var++;
}
echo changeme();
echo changeme();
echo changeme();
?>


a) 678
b) 567
c) 555
d) None of these


Solution: any guesses?
its b) 567

Thursday, December 29, 2011

What is the value of $a?

<?php
$a=123==0123;
?>

What is the value of $a?
a)123
b)True
c)False
d)None of these

Solution: c)False
guess how!!!