PHP Questions

PHP questions suitable for use in interviews or just for fun.

PHP Question: Post Variables

Friday, July 29, 2011 - 18:10

Question

Take the following HTML form.

1
2
3
4
<form id="form" name="form" method="post">
<input type="text" name="number" value="0" />
<input type="submit" />
</form>

What is the output of the following PHP code after the above form has been submitted, and why?

1
2
3
4
5
if ($_POST['number'] === 0) {
        echo 'number is zero';
} else {
        echo 'number is not zero';
}
Category: 

PHP Question: While And Do While Looping

Monday, May 16, 2011 - 23:09

Question

What does the $count variable equal after each of these loops?

1
2
3
4
5
6
// Loop 1 - while
$count = 0;
 
while ($count < 0) {
    ++$count;
}
1
2
3
4
5
6
// Loop 2 - do while
$count = 0;
 
do {
    ++$count;
} while  ($count < 0);
Category: 

PHP Question: Class Methods

Wednesday, May 4, 2011 - 22:19

Question

What is the difference between these two lines of code and can you produce the background code used for them?

1
2
3
4
5
// Line 1
$MyClass->MyMethod();
 
// Line 2
MyClass::MyMethod();
Category: 

PHP Question: PHP Script Shape

Sunday, May 1, 2011 - 22:58

Question

Write a PHP script that will print out the following text in the correct diamond shape.

1
2
3
4
5
6
7
8
9
10
    *
   ***
  *****
 *******
*********
*********
 *******
  *****
   ***
    *
Category: 

PHP Question: Print Object

Thursday, April 28, 2011 - 12:29

Question

The following code was executed.

1
2
3
4
5
6
7
<?php
class MyClass {
  private $foo = "bar";
}
 
$myObject = new MyClass();
echo $myObject;

Which produced the following error.

1
2
3
4
Catchable fatal error: Object of class MyClass could not be converted to string in test.php on line 7
 
Call Stack:
    0.0011     323736   1. {main}() /test.php:0

How can the code be simply changed to prevent this error and produce some form of result?

Category: