Php interview questions by barkamlesh

VIEWS: 167 PAGES: 15

									How do I find the size of an array?

You can find the number of values in an array using the function count, like this:

<?php

$values = range("A","Z");

echo count($values);

?>

This will print "26" to the screen.

Alternatively you can use sizeof($arrayname) instead - it will return the same result.

How do I pick a random value from an array?

If you want to choose an entry randomly from an array then you can use the array_rand function like
this:

<?php

$lottery = range(1,49);

$onenumber = array_rand($lottery);

echo "One number is: $onenumber\n\n";

?>

This will print a random number between 1 and 49.

You can also use array_rand to return a certain number of random numbers.

People often like to write a little computer program to generate their weekly lottery numbers for them.
Here's how to create a lottery number generator for the UK lottery that picks six random numbers
between 1 and 49 in just one line of PHP code:

<?php

foreach(array_rand(range(1,49),6) as $number) echo "$number ";

?>

This will print a random selection of six numbers to the screen, for instance:

27 33 48 21 19 43

How do I remove an element from an array without changing the index values for the rest of the array?
If you want to completely remove a value from an array, then you should unset it.

For instance, if you create an array of the numbers from A - Z then the index values are 0 - 25.

If you then unset the value at index 2 (C) then the rest of the array keeps its index - value correlation
intact.

<?php

$letters = range("A","Z");

unset($letters[2));

print_r($letters);

?>

Copy and paste that to see the results... if that wasn't the question you were asking then please re-post
with more explicit details of what you're looking for.

How do I remove and view the last element of an array?

PHP expected you would want to do this quite often, and so there is a function that enables you to do
just this. The function is called array_pop, and it works a little like this:

<?php

$values = array("I","Like","Sentences","That","Don't","Finish");

$discard = array_pop($values);

echo "Bye bye to $discard...\n\n";

$sentence = implode(" ",$values);

echo "$sentence";

?>

Which gives us the following output:

Bye bye to Finish...

I Like Sentences That Don't

How do I remove the first element from an array?

Often with an array the key of the first element in the array won't simply be '0'.
Often you want to add or remove values from the start or end of an array. To remove the first value in
the array and see what it is, you can use the array_shift function in PHP:

<?php

$values = array(1,2,3,4,5,6,7,8,9,10);

$first = array_shift($values);

echo "First value was: $first";

print_r($values);

?>

Which tells us this:

First value was: 1

Array

(

[0] => 2[1] => 3[2] => 4[3] => 5[4] => 6[5] => 7[6] => 8[7] => 9[8] => 10

Notice how the keys get re-assigned after the call to array_shift, so that '2' now has a key of zero
whereas in the initial array that key referenced the number '1' which has now been removed from the
array.

How do I return all the values in an array?

Sometimes the relationship between the key and the value in an array will be of importance to us, but
often that is not the case and all we really want to concentrate on are the values in the array.

For times like this, PHP provides us with the array_values function, which will simply return is an array
containing the values, like so:

<?php

$example = array(572=>"i","don't","care","much","for","keys");

print_r($example);

$values = array_values($example);

print_r($values);

?>
Which prints:



Array ([572] => i[573] => don't[574] => care[575] => much[576] => for[577] => keys)Array([0] => i[1] =>
on't[2] => care[3] => much[4] => for[5] => keys)

You can see that the keys from the initial array are gone, but if we weren't interested in those then
that's just fine!




How do I reverse sort an array by key?



Use the 'k' for 'key', the 'r' for reverse and 'sort' for well 'sort' and what do you get it?



You guessed it... krsort - getting good at this PHP lark now!



Here's the obligatory quick example:



<?php

$myworld = array("a"=>"PHP","b"=>"learning","c"=>"I'm");

krsort($myworld);

print_r($myworld);

?>

Which confirms your suspicions:

Array([c] => I'm[b] => learning[a] => PHP)

How do I reverse sort the members of an array?

If you wish to reverse sort the members of an array by their values, then you need to use rsort, for
reverse sort, instead of sort.
Again this takes the name of the array as its parameter and here's a little example for you:

<?php

$myworld = array("it","better","make","you");

rsort($myworld);

print_r($myworld);

?>

printing to the screen:

Array([0] => you[1] => make[2] => it[3] => better)

How do I sort alphanumeric array data correctly?

A human would often sort alphanumeric strings differently to the default functions in a computer
language.

Therefore, when you want to sort such items as a human may, it is often referred to as natural sorting.

For instance, look at this output:

<?php

$numbers = array("1.gif","2.gif","20.gif","10.gif");

sort($numbers);

print_r($numbers);

?>



Array

(

[0] => 1.gif[1] => 10.gif[2] => 2.gif[3] => 20.gif)

If you were sorting the filenames in order, you would put 1.gif, 2.gif with 10.gif and 20.gif coming later.
However the default sort algorithm doesn't do this, as you can see.



So if you want to sort in 'natural order' then you're in luck, because PHP provides the natsort function to
save you having to write a clever function yourself, and this will do just what you want here:
<?php

$numbers = array("1.gif","2.gif","20.gif","10.gif");

natsort($numbers);

print_r($numbers);

?>



Which this time prints just what we're after:

Array([0] => 1.gif[1] => 2.gif[3] => 10.gif[2] => 20.gif)

How do I reverse the order of the elements in an array?

This is easy to do in PHP - as with most common things you might like to do with an array, there is
already a nice PHP function to take the strain for you. So no need to concoct your own function - just
use the built-in power of PHP to do it for you, a little like this:

<?php

$countup = range(1,5);

print_r($countup);

$countdown = array_reverse($countup);

print_r($countdown);

?>



This will output the following:

Array([0] => 1[1] => 2[2] => 3[3] => 4[4] => 5)

Array([0] => 5[1] => 4[2] => 3[3] => 2[4] => 1)

How do I sort an array by key?

The key to sorting by key, is to add a k before the sort to get the function ksort.

This takes the name of the array as the parameter, and works like this:
<?php

$myworld = array("c"=>"better","a"=>"make","b"=>"me");

print_r($myworld);

?>



This prints:

Array

([c] => better[a] => make[b] => me)

We need to use ksort to get the right key order:

<?php

$myworld = array("c"=>"better","a"=>"make","b"=>"me");

ksort($myworld);

print_r($myworld);

?>



Array

([a] => make[b] => me[c] => better)

I want to invert my array, can I do this?

The answer is yes, but it depends what you mean by invert. On clarification you wanted to amend the
array so that the values and keys switched over, and this is done through using the function array_flip,
like this:

<?php

$values = array("Fred","Bob","George");

print_r($values);

$values = array_flip($values);

print_r($values);?>
Which returns:

Array([0] => Fred[1] => Bob[2] => George)

Array([Fred] => 0[Bob] => 1[George] => 2)

I have an array of numbers and many repeat, how to list all items in order of maximum occurence?

To do this you will want to use the excellent built-in PHP function called array_count_values that saves
the hassle of coding this yourself like you have to do in many other languages.

Again this is one of the great things about PHP, there is a function in place to do most common tasks so
that you don't have to write the code yourself!

I get a PHP error - maximum execution time exceeded. What is this?

This error again tells you exactly what has happened. Basically the script has taken longer to execute
than the execution time in place for the server.

Now, if nothing major is going on in your script then it could be you have something like an infinite loop
- check carefully. If you expect the script to take a long time to run, but want it to do so, then you will
need to up the time on the server.

If you want to set to infinite time, you can add a line at the top of the script:

set_time_limit(0);



Note that depending on settings you may need to do this in your php.ini file if you have access to it.

How do I remove HTML tags from a string?

To do this, pass the string through the strip_tags function, and it'll clean it up for you like so:

<?php

$mystring = "I said <ignore me then!>you <b>are a little bit</b> whack!";

echo strip_tags($mystring);

?>

Which prints:

I said you are a little bit whack!

How to get the contents of a web page using php?
you can achieve this using curl in php see the example below. function curl_get_con_url($url,
$user_agent = '', $referer = '') { // create a new CURL resource $ch = curl_init(); // set URL and other
appropriate options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false);
/* This lines will make sure that you can save the web page into a variable */ curl_setopt($ch,
CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CUR....!

What is the difference between include and include_once?

include() The include() statement includes and evaluates the specified file. This also applies to require().
The two constructs are identical in every way except how they handle failure. include() produces a
Warning while require() results in a Fatal Error. In other words, use require() if you want a missing file to
halt processing of the page. include() does not behave this way, the script will continue regardless.
include_once() The include_once() statement includes and evaluates the specified file during the
execution ....!

Which of the following represents the proper way to set a session variable?

A. $_SESSION*‘foo’+ = ‘bar’; B. session_start(); C. session_set_save_handler (‘myopen’, ‘myclose’,
‘myread’, ‘mywrite’, ‘mydelete’, ‘mygarbage’); D. $foo = $_SESSION*‘foo’+; Answer A is correct. Answer B
is incorrect because session_start() only activates PHP sessions for the current script. Answer C is
incorrect because session_set_save_handler() al....!

Is MySQL better than MSSQL ?

Mysql is the most popular open source database server right now. It is used by large enteprise level
companies and small, single websites. Is mysql actually better? --------------------------------- Mysql 5.0 vs.
Microsoft SQL 2005 --------------------------------- Features * Mysql 5.X now offers support for cursors,
complete views, and stored procedures. However, Foreign Key support is still in its early stages. * SQL
2005 has native support for xml, multi-dimensional data queryi....!

Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()?

Persistent database connections work only in the module installation of PHP. If you ask for a persistent
connection in the CGI version, you will simply get a regular connection. if you become convinced that
the sheer overhead of opening new database connections is killing your performance, you might want to
investigate opening persistent connections.Unlike regular database connections, these connections are
not automatically killed when your page exits (or even when mysql_close() is called) but are saved ....!

php comments will be?

a) // b) /* fgfg */ c) All of the above d) First one ANS: All of the above ....!

What's foreign data in php?

* Anything from a form* Anything from $_GET, $_POST, $_REQUEST* Cookies ($_COOKIES)* Web
services data* Files* Some server variables (e.g. $_SERVER['SERVER_NAME'])* Environment variables*
Database query results Filter supports get, post, cookies, server and environment variables as well as
defined variables (server support may not work in all sapi, for filter 0.11.0 or php 5.2.0). ....!

what is the output below mentioned

<? $text = 'php m programmer'; echo strpbrk($text, 'm'); ?> a) mmer b) mer c) all of the above d) none
of the above ANS: none of the above NOTE: if we execute the above code we get the output as 'm
programmer' ....!

What is the maximum length for database, table & column names?

database- 64table -64columns-64alias-255 ....!

How do I prevent Web browsers caching a page in php?

<?php header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Pragma: no-cache'); ?>         ....!

current version of php

PHP 5.3.2 Released! ....!

Tell me some thing about mod_rewrite and url rewriting?

mod_rewrite*************Simply, mod_rewrite is used for rewriting a URL at the server level, giving
the user output for that final page. So, for example, a user may ask for
http://www.referads.com/example/blue/, but will really be given
http://www.referads.com/example.php?colour=blue by the server. Of course, the user will b....!

What is meant by Session Clustering?

The Session Manager session support allows multiple server instances to share a common pool of
sessions, known as a session cluster Session clustering setting up methods : #1)First methods, is to have
a NFS shared where session will be store. Setting this is quite easy, just a little modification on php.ini
file to change the “session.save_path ? directive to point to the NFS share. The main problem with NFS
is on high traffic, NFS share is really slow. So synchronisation and data corruption can arrive and ....!

What function would you use to redirect the browser to a new page?

1. redir() 2. header() 3. location() 4. redirect() ANS:header() ....!

List out some session functions in php?

session_save_path -- Get and/or set the current session save path session_is_registered -- Find out
whether a global variable is registered in a session session_unset -- Free all session variables
session_cache_expire -- Return current cache expire session_cache_limiter -- Get and/or set the current
cache limiter session_commit -- Alias of session_write_close() session_decode -- Decodes session data
from a string session_destroy -- Destroys all data registered to a sessi....!
session_save_path -- Get and/or set the current session save path



session_is_registered -- Find out whether a global variable is registered in a session



session_unset -- Free all session variables



session_cache_expire -- Return current cache expire



session_cache_limiter -- Get and/or set the current cache limiter



session_commit -- Alias of session_write_close()



session_decode -- Decodes session data from a string



session_destroy -- Destroys all data registered to a sessi....!



« General Java Servlet questions

10 bottles of pills »

PHP interview questions and answers

By admin | December 12, 2005



 1. What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to the
browser.

  2. What’s the difference between include and require? - It’s how they handle failures. If the file is not
found by require(),
it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a
warning will be issued, but execution will continue.

 3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number,
what’s the problem? - PHP Interpreter treats numbers

beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.



 4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?

- In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something

like "{$a},000,000 mln dollars", then you definitely need to use the braces.



5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);

 6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b

  7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything
to

the integer type, so numbers 10 and 11 will be compared.

  8. When are you supposed to use endif to end the conditional statement? - When the original if was
followed by :

and then the code block without braces.

  9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s
true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

 10. How do I find out the number of parameters passed into function? - func_num_args() function
returns the number of parameters passed in.

 11. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? -
100, it’s a reference to existing variable.

 12. What’s the difference between accessing a class method via -> and via ::? - :: is allowed to access
methods that can perform static operations, i.e. those, which do not require object initialization.

 13. Are objects passed by value or by reference? - Everything is passed by value.

 14. How do you call a constructor for a parent class? - parent::constructor($value)
 15. What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the
variables than need to be saved, while __wakeup retrieves them.

 16. Why doesn’t the following code print the newline properly? <?php

          $str = ‘Hello, there.nHow are you?nThanks for visiting TechInterviews’;

          print $str;

     ?>

   Because inside the single quotes the n character is not interpreted as newline, just as a sequence of
two characters - and n.

 17. Would you initialize your strings with single quotes or double quotes? - Since the data inside the
single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to
initialize a string with single quotes, unless you specifically need variable substitution.

 18. How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents:
$arr*1+*2+"; ?> doesn’t for two-dimensional array of mine? - Any time you have an array with more than
one dimension, complex parsing syntax is required. print "Contents: ,$arr*1+*2+-" would’ve worked.

 19. What is the difference between characters ?23 and x23? - The first one is octal 23, the second is hex
23.

 20. With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.

 21. I want to combine two variables together:



    $var1 = 'Welcome to ';

    $var2 = 'TechInterviews.com';



   What will work faster? Code sample 1:



   $var 3 = $var1.$var2;



   Or code sample 2:
   $var3 = "$var1$var2";



    Both examples would provide the same result - $var3 equal to "Welcome to TechInterviews.com".
However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via
concatenating small sets a million times or so), and you will see that concatenation works significantly
faster than variable substitution.

 22. For printing out strings, there are echo, print and printf. Explain the differences. - echo is the most
primitive of them, and just outputs the contents following the construct to the screen. print is also a
construct (so parentheses are optional when calling it), but it returns TRUE on successful output and
FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

    <?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?>

     and it will output the string "Welcome to TechInterviews!" print does not take multiple parameters.
It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might
not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages
as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

 23. I am writing an application in PHP that outputs a printable version of driving directions. It contains
some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50
characters. How do I accomplish that with PHP? - On large strings that need to be formatted according
to some length specifications, use wordwrap() or chunk_split().

 24. What’s the output of the ucwords function in this example?

        $formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS");

        print $formatted;

   What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.

   ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To
avoid this, and get a properly formatted string, it’s worth using strtolower() first.

 25. What’s the difference between htmlentities() and htmlspecialchars()? - htmlspecialchars only takes
care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of
character sequences that have different meaning in HTML.

 26. What’s the difference between md5(), crc32() and sha1() crypto on PHP? - The major difference is
the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and
md5() returns a 160 bit value. This is important when avoiding collisions.

 27. So if md5() generates the most secure hash, why would you ever use the less secure crc32() and
sha1()? - Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data
that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the
160-bit value to save on space. Second,

the more secure the crypto is, the longer is the computation time to deliver the hash value. A high
volume site might be significantly slowed down, if frequent md5() generation is required.

								
To top