TechSchool
Home / Interview questions / PHP

PHP interview questions

59 questions about PHP with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.

Basics

1. What is PHP?

PHP is a server-side scripting language for web pages. The server runs the PHP code and sends HTML to the browser.

<?php
echo "Hello, World!";
?>

Full lesson: Php intro

2. How do you write PHP code in a file?

PHP code starts with <?php and ends with ?>. You can mix PHP code with HTML in one file.

<?php
echo "My first PHP script";
?>

Full lesson: Php syntax

3. How do you make a string variable in PHP?

Write a dollar sign, then the name, then the value in quotes. Use single or double quotes for text.

<?php
$name = "Anna";
echo $name;
?>

Full lesson: Php string

4. How do you write an if...else statement in PHP?

Put the condition in round brackets after if. Put each block in curly braces. The else block runs when the condition is false.

<?php
$age = 20;
if ($age >= 18) {
  echo "Adult";
} else {
  echo "Child";
}
?>

Full lesson: Php if else

5. How do you repeat code with a while loop in PHP?

The while loop runs its block while the condition is true. Change the counter inside the loop to stop it.

<?php
$i = 1;
while ($i <= 3) {
  echo $i;
  $i++;
}
?>

Full lesson: Php looping

6. How do you create an array in PHP?

Use the array() function or the short square bracket syntax. Each value gets a numeric key that starts at 0.

<?php
$colors = array("red", "green", "blue");
echo $colors[1];
?>

Full lesson: Php arrays

7. How do you check if a variable is an array?

Call is_array() with the variable. The function returns TRUE for an array and FALSE for other types.

<?php
$arr = array("a", "b");
var_dump(is_array($arr));
?>

Full lesson: Php is array function

8. How do you check if a variable is a string?

Call is_string() with the variable. The function returns TRUE when the value is a string.

<?php
var_dump(is_string("99"));
var_dump(is_string(123.05));
?>

Full lesson: Php is string function

9. How do you check if a variable is an object?

Call is_object() with the variable. The function returns TRUE when the value is an object.

<?php
$obj = new stdClass;
var_dump(is_object($obj));
?>

Full lesson: Php is object function

10. How do you get the type of a variable?

Call gettype() with the variable. It returns a string such as integer, string, or array.

<?php
echo gettype(102);
echo gettype("text");
?>

Full lesson: Php gettype function

11. How do you change the type of a variable?

Call settype() with the variable and the new type name. The function changes the variable in place and returns TRUE on success.

<?php
$foo = "5bar";
settype($foo, "integer");
echo $foo;
?>

Full lesson: Php settype function

12. How do you join array elements into one string?

Call join() with a separator and the array. The function puts the separator between each element.

<?php
$arr = array('Hello','World!');
echo join(" ", $arr);
?>

Full lesson: Func string join

13. How do you merge two arrays into one array?

Call array_merge() with both arrays. If two elements share a key, the last value wins.

<?php
$a1 = array("a" => "red", "b" => "green");
$a2 = array("c" => "blue", "b" => "yellow");
print_r(array_merge($a1, $a2));
?>

Full lesson: Func array merge

14. How do you find values in one array that are not in another array?

Call array_diff() with the first array and the second array. The function returns the values that are only in the first array.

<?php
$a1 = array("red", "green", "blue");
$a2 = array("red", "green");
print_r(array_diff($a1, $a2));
?>

Full lesson: Func array diff

15. How do you assign array values to variables in one step?

Use list() on the left side and the array on the right side. This works only for arrays with numeric keys.

<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo $a;
?>

Full lesson: Func array list

16. How do you remove the first element of an array?

Call array_shift() with the array. The function removes the first element and returns its value.

<?php
$a = array("red", "green", "blue");
echo array_shift($a);
print_r($a);
?>

Full lesson: Func array shift

17. How do you add new values to the start of an array?

Call array_unshift() with the array and the new values. Numeric keys restart from 0 after the insert.

<?php
$a = array("red", "green");
array_unshift($a, "blue");
print_r($a);
?>

Full lesson: Func array unshift

18. How do you compare two arrays with your own function?

Call array_udiff() with both arrays and your function name. Your function decides which values are equal.

<?php
function myfunction($a,$b) {
  if ($a===$b) { return 0; }
  return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green");
$a2=array("a"=>"blue","b"=>"black");
print_r(array_udiff($a1,$a2,"myfunction"));
?>

Full lesson: Func array udiff

19. How do you get the type of a file or directory?

Call filetype() with the path. It returns a word such as file or dir, or FALSE on failure.

<?php
echo filetype("test.txt");
?>

Full lesson: Func filesystem filetype

Intermediate

20. How do you get the color of a pixel in an image?

Call imagecolorsforindex() with the image and a color index. It returns an array with red, green, blue, and alpha keys.

<?php
$im = imagecreatefrompng('example-logo.png');
$color_index = imagecolorat($im, 40, 20);
print_r(imagecolorsforindex($im, $color_index));
?>

Full lesson: Php imagecolorsforindex

21. How do you run a SQL query with PDO?

Call the query() method on the PDO object with your SQL string. The method returns a statement object for the result.

<?php
$pdo = new PDO('sqlite::memory:');
$stmt = $pdo->query('SELECT 1 AS n');
print_r($stmt->fetch());
?>

Full lesson: Pdo query

22. How do you save a database transaction with PDO?

Call beginTransaction() before your queries. Then call commit() to save all changes at once.

<?php
$pdo->beginTransaction();
$pdo->exec("INSERT INTO users (name) VALUES ('Ann')");
$pdo->commit();
?>

Full lesson: Pdo commit

23. Why is it a mistake to use gettype() to test a type?

The returned string can change in future PHP versions. Use an is_* function such as is_array() instead.

<?php
if (is_array($data)) {
  echo "This is an array";
}
?>

Full lesson: Php gettype function

24. Why is it a mistake to call list() on an array with string keys?

The list() function works only for numerically indexed arrays. String keys do not fill the variables.

<?php
$my_array = array("a" => "Dog", "b" => "Cat");
list($x, $y) = $my_array;
var_dump($x);
?>

Full lesson: Func array list

25. Why is it a mistake to ignore key collisions in array_merge()?

When two arrays share a key, the last value overwrites the earlier value. Check your keys before you merge.

<?php
$a1 = array("b" => "green");
$a2 = array("b" => "yellow");
print_r(array_merge($a1, $a2));
?>

Full lesson: Func array merge

26. Why is it a mistake to expect array_shift() to keep numeric keys?

The function gives all numeric keys new numbers that start from 0. String keys stay the same.

<?php
$a = array(1, 2, 3);
array_shift($a);
print_r($a);
?>

Full lesson: Func array shift

27. Why is it a mistake to call join() with the array first?

The separator must come before the array. Put the arguments in the wrong order and the output is wrong.

<?php
$arr = array('Hello','World!');
echo join(" ", $arr);
?>

Full lesson: Func string join

28. Why is it a mistake to trust cached filetype() results?

The function caches its result. Call clearstatcache() after a file changes.

<?php
clearstatcache();
echo filetype("test.txt");
?>

Full lesson: Func filesystem filetype

29. Why is it a mistake to call imagecolorsforindex() with a pixel value instead of an index?

The function needs a color index from imagecolorat(). Pass the pixel result directly to get the color array.

<?php
$im = imagecreatefrompng('example-logo.png');
$idx = imagecolorat($im, 40, 20);
print_r(imagecolorsforindex($im, $idx));
?>

Full lesson: Php imagecolorsforindex

30. How do you open a file in PHP?

You call fopen() with a file name and a mode. The mode sets read or write access. The function returns a file handle.

<?php
$file = fopen("welcome.txt", "r");
?>

Full lesson: Php file

31. How do you get the type of a resource in PHP?

You call get_resource_type() with a resource handle. The function returns a string that names the resource type. An invalid handle causes an error.

<?php
$fp = fopen("foo", "w");
echo get_resource_type($fp);
?>

Full lesson: Php get resource type function

32. How do you get image size information from image data in a string?

You call getimagesizefromstring() with the image data. The function returns an array with size and type information. It works like getimagesize() but takes a string, not a file name.

<?php
$data = file_get_contents("example-logo.png");
$info = getimagesizefromstring($data);
print_r($info);
?>

Full lesson: Php getimagesizefromstring

33. How do you draw an elliptical arc on an image in PHP?

You call imagearc() with the image, center point, size, angles, and color. The function draws the arc on the image. You need the GD library.

<?php
$im = imagecreatetruecolor(200, 200);
$white = imagecolorallocate($im, 255, 255, 255);
imagearc($im, 100, 100, 150, 100, 0, 360, $white);
?>

Full lesson: Php imagearc

34. How do you handle errors in PHP with the die() function?

You call die() with a message when an operation fails. The script stops and sends the message. This is a simple error handling method.

<?php
$file = fopen("welcome.txt", "r") or die("Cannot open file.");
?>

Full lesson: Php error

35. What is the purpose of the import_request_variables() function?

It imports GET, POST, and Cookie variables into the global scope. The function is no longer supported in recent PHP versions. Do not use it in new code.

<?php
import_request_variables("gp", "prefix_");
?>

Full lesson: Php import request variables function

36. Why is it a mistake to use import_request_variables() in new PHP code?

The function is removed from recent PHP versions. Your code will fail on those versions. Use $_GET, $_POST, and $_COOKIE instead.

Full lesson: Php import request variables function

37. Why is it a mistake to call get_resource_type() with a closed resource?

A closed resource is no longer a valid resource. The function raises an error for an invalid handle. Check the resource before you call the function.

Full lesson: Php get resource type function

38. Why is it a mistake to call getimagesizefromstring() with a file name?

The function expects image data in a string, not a file path. A file name string is not valid image data. The function fails and returns false.

Full lesson: Php getimagesizefromstring

39. Why is it a mistake to call imagearc() without the GD library?

The image functions need the GD extension. Without GD, the function is undefined. Your script stops with a fatal error.

Full lesson: Php imagearc

Common mistakes

40. Why is it a mistake to ignore the return value of fopen()?

fopen() returns false when it cannot open the file. If you do not check the result, later file operations fail. Always test the handle before you use it.

Full lesson: Php file

41. Why is it a mistake to call die() without a message on failure?

A message helps you find the cause of the error. Without a message, the script stops with no clear reason. Add a short text to die().

Full lesson: Php error

42. Why is it a mistake to use the "w" mode when you want to read a file?

The "w" mode clears the file contents. It also creates a new file if the file does not exist. Use "r" for read-only access.

Full lesson: Php file

43. Why is it a mistake to call get_resource_type() on a variable that is not a resource?

The function needs a valid resource handle. A string or number is not a resource. The function raises an error for an invalid parameter.

Full lesson: Php get resource type function

44. Why is it a mistake to skip error checks in file code?

File operations can fail for many reasons, such as a missing file. Without error checks, the script continues with bad data. Add checks after each file call.

Full lesson: Php error

45. What does PHP code return to the browser?

PHP code runs on the server. The server sends only the plain result to the browser.

<?php echo "Hello, PHP!"; ?>

Full lesson: Php intro

46. What is the default file extension for a PHP file?

The default file extension is .php. A web server parses this file for PHP code.

Full lesson: Php syntax

47. How do you store many values in one variable?

Use an array. An array holds many values in one variable.

$cars = array("Volvo", "BMW", "Toyota");

Full lesson: Php arrays

48. What are the three types of arrays in PHP?

The three types are numeric, associative, and multidimensional. A numeric array uses number keys. An associative array uses named keys.

Full lesson: Func array

49. How do you print one value from an array?

Use the key in square brackets. The first item has key 0.

$cars = array("Volvo", "BMW"); echo $cars[0];

Full lesson: Php arrays

50. How do you run PHP on your own computer?

Install a web server, PHP, and a database. The official PHP site gives the steps.

Full lesson: Php install

51. What does the array() function do?

The array() function creates an array. You can give values or key and value pairs.

$a = array("name" => "Tom", "age" => 20);

Full lesson: Func array

52. How do you read a file in PHP?

Open the file with fopen() in read mode. Then read the data with a read function.

$f = fopen("test.txt", "r"); $data = fread($f, filesize("test.txt")); fclose($f);

Full lesson: Php file

53. How do you start a database transaction with PDO?

Call beginTransaction() on the PDO object. This turns off auto-commit for the next statements.

$dbh->beginTransaction();

Full lesson: Pdo commit

54. How do you draw an arc on an image with PHP?

Use imagearc() on an image resource. Give the center, width, height, start angle, end angle, and color.

$img = imagecreatetruecolor(200, 200); $white = imagecolorallocate($img, 255, 255, 255); imagearc($img, 100, 100, 150, 150, 0, 180, $white);

Full lesson: Php imagearc

55. Why is it a mistake to call array_merge() and expect number keys to stay the same?

array_merge() renumbers numeric keys. The old number keys do not stay. Use the + operator to keep keys.

$a = array(5 => "x"); $b = array(5 => "y"); print_r($a + $b);

Full lesson: Func array merge

56. Why is it a mistake to call array_unshift() and expect the old numeric keys to stay?

array_unshift() gives new number keys to all items. The old keys are lost. Use string keys if you need stable keys.

$a = array(1 => "a", 2 => "b"); array_unshift($a, "z"); print_r($a);

Full lesson: Func array unshift

57. Why is it a mistake to call settype() on a variable you still need as an array?

settype() changes the variable in place. The old array data is gone. Make a copy first if you need both.

$a = array(1, 2); settype($a, "string"); echo $a;

Full lesson: Php settype function

58. Why is it a mistake to call PDO::commit() without beginTransaction()?

commit() needs an open transaction. Without one, the call fails and returns false. Always start the transaction first.

$dbh->beginTransaction(); $dbh->commit();

Full lesson: Pdo commit

59. Why is it a mistake to call imagecolorsforindex() on a truecolor image?

imagecolorsforindex() works on palette images only. A truecolor image has no color index. Use imagecolorat() to read a truecolor pixel.

$rgb = imagecolorat($img, 10, 10); $c = imagecolorsforindex($img, $rgb);

Full lesson: Php imagecolorsforindex

More on TechSchool
See the PHP cheat sheet Python JavaScript TypeScript HTML CSS React Vue 3 Node.js Java C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures