Sharag Web

Get All Information

PHP Interview Questions part 6 [asked in YAHOO interview]


  1. Which of the following will NOT add john to the users array?

    1. $users[ ] = ‘john’;
    2. Successfully adds john to the array

    3. array_add($users,’john’);
    4. Fails stating Undefined Function array_add()

    5. array_push($users,‘john’);
    6. Successfully adds john to the array

    7. $users ||= ‘john’;
    8. Fails stating Syntax Error

  2. What’s the difference between sort(), asort() and ksort? Under what circumstances would you use each of these?

    1. sort()
      Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length – 1. This is used primarily on arrays where the indexes/keys do not matter.
    2. asort()
      Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.
    3. ksort()
      Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.
  3. What would the following code print to the browser? Why?

    PHP:

    1. $num = 10;
    2. function multiply(){
    3. $num = $num * 10;
    4. }
    5. multiply();
    6. echo $num; // prints 10 to the screen

    Since the function does not specify to use $num globally either by using global $num; or by $_GLOBALS[‘num’] instead of $num, the value remains 10.

  4. What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?

    Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.
    Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.

    PHP:

    1. $myVariable = “its’ value”;
    2. Myfunction(&$myVariable); // Pass by Reference Example

    So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.

  5. What functions can you use to add library code to the currently running script?

    This is another question where the interpretation could completely hit or miss the question. My first thought was class libraries written in PHP, so include(), include_once(), require(), and require_once() came to mind. However, you can also include COM objects and .NET libraries. By utilizing the com_load and the dotnet_load respectively you can incorporate COM objects and .NET libraries into your PHP code, thus anytime you see “library code” in a question, make sure you remember these two functions.

  6. What is the difference between foo() & @foo()?

    foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.
    @foo() will mask any parse/syntax/thrown errors as it executes.
    You will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query. However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.

  7. How do you debug a PHP application?

    This isn’t something I do often, as it is a pain in the butt to setup in Linux and I have tried numerous debuggers. However, I will point out one that has been getting quite a bit of attention lately.
    PHP – Advanced PHP Debugger or PHP-APD. First you have to install it by running:
    pear install apd
    Once installed, start the trace by placing the following code at the beginning of your script:
    apd_set_pprof_trace();
    Then once you have executed your script, look at the log in apd.dumpdir.
    You can even use the pprofp command to format the data as in:
    pprofp -R /tmp/pprof.22141.0
    For more information see http://us.php.net/manual/en/ref.apd.php

  8. What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?

    The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false. Such functions would be strpos and strrpos.
    I am having a hard time with the second portion, as I am able to come up with scenarios where ‘==’ will be false and ‘===’ would come out true, but it’s hard to think of the opposite. So here is the example I came up with:

    PHP:

    1. if (strpos(“abc”, “a”) == true)
    2. {
    3. // this does not get hit, since “a” is in the 0 index position, it returns false.
    4. }
    5. if (strpos(“abc”, “a”) === true)
    6. {
    7. // this does get hit as the === ensures this is treated as non-boolean.
    8. }
  9. How would you declare a class named “myclass” with no methods or properties?

    PHP:

    1. class myclass
    2. {
    3. }
  10. How would you create an object, which is an instance of “myclass”?

    PHP:

    1. $obj = new myclass();

    It doesn’t get any easier than this.

  11. How do you access and set properties of a class from within the class?

    You use the $this->PropertyName syntax.

    PHP:

    1. class myclass
    2. {
    3. private $propertyName;
    4. public function __construct()
    5. {
    6. $this->propertyName = “value”;
    7. }
    8. }
    1. What is the difference between include, include_once? and require?

      All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.

      1. include()
        The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
      2. include_once()
        include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
      3. require()
        Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.
    2. What function would you use to redirect the browser to a new page?

      1. redir()
        This is not a function in PHP, so it will fail with an error.
      2. header()
        This is the correct function, it allows you to write header data to direct the page to a new location. For example:

        PHP:

        1. header(“Location: http://www.google.com/”);
      3. location()
        This is not a function in PHP, so it will fail with an error.
      4. redirect()
        This is not a function in PHP, so it will fail with an error.
    3. What function can you use to open a file for reading and writing?

      1. fget()
        This is not a function in PHP, so it will fail with an error.
      2. file_open()
        This is not a function in PHP, so it will fail with an error.
      3. fopen()
        This is the correct function, it allows you to open a file for reading and/or writing. In fact, you have a lot of options, check out php.net for more information.
      4. open_file()
        This is not a function in PHP, so it will fail with an error.
    4. What’s the difference between mysql_fetch_row() and mysql_fetch_array()?

      mysql_fetch_row() returns all of the columns in an array using a 0 based index. The first row would have the index of 0, the second would be 1, and so on. Now another MySQL function in PHP is mysql_fetch_assoc(), which is an associative array. Its’ indexes are the column names. For example, if my query was returning ‘first_name’, ‘last_name’, ’email’, my indexes in the array would be ‘first_name’, ‘last_name’, and ’email’. mysql_fetch_array() provides the output of mysql_fetch_assoc and mysql_fetch_row().

    5. What does the following code do? Explain what’s going on there.

      PHP:

      1. $date=’09/25/2008′;
      2. print ereg_replace(“([0-9]+)/([0-9]+)/([0-9]+)”,\\2/\\1/\\3″,$date);

      This code is reformatting the date from MM/DD/YYYY to DD/MM/YYYY. A good friend got me hooked on writing regular expressions like below, so it could be commented much better, granted this is a bit excessive for such a simple regular expression.

      PHP:

      1. // Match 0-9 one or more times then a forward slash
      2. $regExpression = “([0-9]+)/”;
      3. // Match 0-9 one or more times then another forward slash
      4. $regExpression .= “([0-9]+)/”;
      5. // Match 0-9 one or more times yet again.
      6. $regExpression .= “([0-9]+)”;

      Now the \\2/\\1/\\3 denotes the parentheses matches. The first parenthesis matches the month, the second the day, and the third the year.

    6. Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?

      First of all why would you write a regular expression when a PHP function already exists? See php.net’s strip_tags function. However, considering this is an interview question, I would write it like so:

      PHP:

      1. $stringOfText = “<p>This is a testing</p>”;
      2. $expression = “/<(.*?)>(.*?)<\/(.*?)>/”;
      3. echo preg_replace($expression, \\2″, $stringOfText);
      4. // It was suggested (by Fred) that /(<[^>]*>)/ would work too.
      5. $expression = “/(<[^>]*>)/”;
      6. echo preg_replace($expression, “”, $stringOfText);
    7. What’s the difference between the way PHP and Perl distinguish between arrays and hashes?

      This is why I tell everyone to, “pick the language for the job!” If you only write code in a single language how will you ever answer this question? The question is quite simple. In Perl, you are required to use the @ sign to start all array variable names, for example, @myArray. In PHP, you just continue to use the $ (dollar sign), for example, $myArray.
      Now for hashes in Perl you must start the variable name with the % (percent sign), as in, %myHash. Whereas, in PHP you still use the $ (dollar sign), as in, $myHash.

    8. How can you get round the stateless nature of HTTP using PHP?

      The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.
      There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.

    9. What does the GD library do?

      This is probably one of my favorite libraries, as it is built into PHP as of version 4.3.0 (I am very happy with myself, I didn’t have to look up the version of PHP this was introduced on php.net). This library allows you to manipulate and display images of various extensions. More often than not, it is used to create thumbnail images. An alternative to GD is ImageMagick, however, unlike GD, this does not come built in to PHP and must be installed on the server by an Administrator.

    10. Name a few ways to output (print) a block of HTML code in PHP?

      Well you can use any of the output statments in PHP, such as, print, echo, and printf. Most individuals use the echo statement as in:

      PHP:

      1. echo “My test string $variable”;

      However, you can also use it like so:

      PHP:

      1. echo <<<OUTPUT
      2. This text is written to the screen as output and this $variable is parsed too. If you wanted you can have <span> HTML tags in here as well.</span> The END; remarks must be on a line of its own, and can‘t contain any extra white space.
      3. END;
    11. Is PHP better than Perl? – Discuss.

      Come on, let’s not start a flame over such a trivial question. As I have stated many times before,

      “Pick the language for the job, do not fit the job into a particular language.”

      Perl in my opinion is great for command line utilities, yes it can be used for the web as well, but its’ real power can be really demonstrated through the command line. Likewise, PHP can be used on the command line too, but I personally feel it’s more powerful on the web. It has a lot more functions built with the web in mind, whereas, Perl seems to have the console in mind.
      Personally, I love both languages. I used Perl a lot in college and I used PHP and Java a lot in college. Unfortunately, my job requires me to use C#, but I spend countless hours at home working in PHP, Perl, Ruby (currently learning), and Java to keep my skills up to date. Many have asked me what happened to C and C++ and do they still fit into my applications from time to time. The answer is primarily ‘No’. Lately all of my development work has been for the web and though C and C++ could be written for the web, they are hardly the language to use for such tasks. Pick the language for the job. If I needed a console application that was meant to show off the performance differences between a quick sort, bubble sort, and a merge sort, give me C/C++! If you want a Photo Gallery, give me PHP or C# (though I personally find .NET languages better for quick GUI applications than web).

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page