LinkedIn PHP Assessment Test

Which code snippet uses the correct syntax for creating an instance of the Pet class?

$cat = new Pet();
all of these answers
$horse = (new Pet);
$dog = new Pet;

Which is the most secure way to avoid storing a password in clear text in a database?

$encrypted = sha1($password)
$encrypted = password_hash($password, PASSWORD_DEFAULT);
$encrypted = md5($password);
$encrypted = crypt($password, $salt);

What does this script do?
1 $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
2 if ($email === false) {
3 $emailErr = "Please re-enter valid email";
4 }

It makes sure the email address is a good and functioning address.
It assigns an email to a variable and then removes all illegal characters from the $email variable.
It verifies that an email address is well formed.
It makes an email safe to input into a database.

What is the purpose of adding a lowercase "u" as a modifier after the final delimiter in a Perl-compatible regular expression?

It inverts the greediness of the quantifiers in the pattern so they are not greedy by default.
It makes the dot metacharacter match anything, including newline characters.
It makes the pattern match uppercase letters.
Both the pattern and subject string are treated as UTF-8.

In the following script, which line(s) will cause an error(s)?
1 <?php
2 $count = 0;
3 $_xval = 5;
4 $_yval = 1.0;
5 $some_string = "Hello there!";
6 $some_string = "How are you?";
7 $will i work = 6;
8 $3blindmice = 3;
9 ?>

Lines 3 and 4 will cause an error because a variable cannot start with an underscore (_).
Lines 7 and 8 will cause an error. Line 7 has whitespace in $will i work and should be $will_i_work. Line 8 cannot start with a number because it is a variable.
Line 6 will cause an error because you can't reassign a new value to a variable that has already been set.
Line 5 will cause an error because some_string should be someString.

What is a key difference between GET and POST?

GET displays the submitted data as part of the URL. During POST, this information is not shown, as it’s encoded in the request body.
GET is used with the HTTP protocol. POST is used with HTTPS.
GET is intended for changing the server state and it carries more data than POST.
GET is more secure than POST and should be used for sensitive information.

What is the value of $total in this calculation?
$total = 2 + 5 * 20 - 6 / 3;


Which value equates to true?


Which are valid PHP error handling keywords?

yield, throw, catch, finally
try, throw, catch, finally
try, throw, catch, callable
try, yield, catch, finally

What causes the "headers already sent" error when using the header() function?

all of these answers
calling echo or print before the header() function
the byte order mark (BOM) at the beginning of the file
extra blank lines after the closing PHP tag on an include file

How can you test if a check box is set?

Use $_GET['test'] == ''.
all of these answers
Use isset($_GET['test'].
Use !empty($_GET['test']).

The _____ operator is useful for sorting operations. It compares two values and returns an integer less than, equal to, or greater than 0 depending on whether the value on the _____ is less than, equal to, or greater than the other.

comparison; left
equality; right
greater-than; right
spaceship; left

What does this code output?
echo 76 &lt;=&gt; '76 trombones';

a parse error

What is the best way to explain what this script does?
1 if (!$_SESSION['myusername'])
2 {
3 header('location: /login.php');
4 exit;
5 }

This script times out the session for myusername.
Cookies are starting to be stored as a result of this script.
This script is on a page that requires the user to be logged in. It checks to see if the user has a valid session.
This script validates the username and password.

For the HTML form below, what is the correct functioning script that checks the input "mail" to be sure it is filled before proceeding?
1 <!DOCTYPE html>
2 <html><body>
3 <form name="new user" method="post" action="step2_check.php">
4 <input type="text" name="mail" required="required"/> <br />
5 <input type="password" name="password" required="required"/><br />
6 <input type="submit" value="continue"/>
7 </form>
8 </body></html>

1 if (empty($_POST["mail"])) {
2 echo "Yes, mail is set";
3 } else {
4 echo "No, mail is not set";
5 }

1 if (!empty($_POST["mail"])) {
2 echo "Yes, mail is set";
3 } else {
4 echo "No, mail is not set";
5 }

1 if (!empty($_POST["mail"])) {
2 echo "Yes, mail is not set";
3 } else {
4 echo "No, mail is set";
5 }

1 if (!empty($_POST "mail" )) {
2 echo "Yes, mail is set";
3 } else {
4 echo "No, mail is not set";
5 }

In a conditional statement, you want to execute the code only if both values are true. Which comparison operator should you use?


In PHP 7, what is the correct way to import multiple classes from the same namespace in a single declaration?

use myApp\myNamespace\[ClassA, ClassB, ClassC];
use myApp\myNamespace\{ClassA, ClassB, ClassC};
use myApp\myNamespace\ClassA, ClassB, ClassC;
use myApp\myNamespace\(ClassA, ClassB, ClassC);

What is missing from this code, which is supposed to create a test cookie?
1 $string_name = " testcookie";
2 $string_value = "This is a test cookie";
3 $expiry_info = time()+259200;
4 $string_domain = "localhost.localdomain";

The call to setcookie() is missing.
The $_COOKIE array is missing.
The cookie session is missing.
The $_REQUEST is missing.

Which database is most commonly used with PHP?


All variables in PHP start with which symbol?


Which two functions can sanitize text and validate text formats?

filter_var() and strstr()
filter_var() and filter_input()
session_start() and filter_input()
preg_match() and session_start()

What is the output of this script?
1 $believable = 'false';
2 $myth = 'The moon is made of green cheese';
3 $calc = 10**3+1;
4 if ($believable) {
5 echo $myth;
6 } else {
7 echo $calc;
8 }

The moon is made of green cheese

To create a new record, use the _____ SQL command. To modify an existing record, use _____. To query data, use _____.


A PDO object called $db has been set up to use for database operations, including user authentication. All user-related properties are set. The script line public function __construct(&$db) shows a constructor that initializes all user-related properties to _____ if no user has logged in. These parameters will be properly set by the login functions when a user logs in.


Assume that $r is 255, and $g and $b are both 0. What is the correct code to output "#ff0000"?

printf('#%2x%2x%2x', $r, $g, $b);
printf('#%02x%02x%02x', $r, $g, $b);
printf('#%x%x%x', $r, $g, $b);
printf('#%2X%2X%2X', $r, $g, $b);

Which loop displays all numbers from 1 to 10 inclusive?

$i = 0;
while ($i < 10) {
echo ++$i . '<br>';

$i = 0;
while ($i <= 10) {
echo ++$i . '<br>';

$i = 1;
while ($i < 10) {
echo $i++ . '<br>';

$i = 0;
while ($i <= 10) {
echo $i++ . '<br>';

You want to use wildcard characters when searching for records in a MySQL/MariaDB database using a PDO prepared statement. Which code should you use?

$statement->bindParam(':name', '%' . $_GET['name'] . '%');
$statement->bindValue(':name', '%' . $_GET['name'] . '%');
$statement->bindParam('%' . $_GET['name'] . '%', ':name');
$statement->bindValue('%' . $_GET['name'] . '%', ':name');

Why is it not recommended to make all of a class's variables public?

The attribute may be accessed only by the class that defines the member.
Doing so makes your code tightly coupled
You will have no control over which values the attribute can take. Any external code will be able to change it without any constraint.
You can then access the attribute only within the class itself, and by inheriting and parent classes.

Which command will extract the domain suffix ("com") from the string $string = "";?

sub($string, -3)
substr($string, 3)
substr($string, -3)

You want to find out what day Twelfth Night falls on after Christmas 2018. Which code should you use?

$twelfth_night = strtotime('December 25, 2018 + 12 days');
echo strftime('%d', $twelfth_night);

$twelfth_night = strtotime('December 25, 2018 + 12 days');
echo date('d', $twelfth_night);

$xmas = new DateTime('Dec 25, 2018');
$twelfth_night = $xmas->add(strtotime('12 days'));
echo $twelfth_night->format('D');

$xmas = new DateTime('Dec 25, 2018');
$twelfth_night = $xmas-&gt;add(new DateInterval('P12D'));
echo $twelfth_night-&gt;format('l');

The following XML document is in books.xml. Which code will output "Historical"?
<title>A Tale of Two Cities</title>
<author>Charles Dickens</author>
<title>Then There Were None</title>
<author>Agatha Christies</author>

$books = new SimpleXMLElement('books.xml');
echo $books->book[0]->categories->category[1];

$books = simplexml_load_string('books.xml');
echo $books->book[0]->categories->category[1];

$books = new SimpleXML('books.xml');
echo $books->book[0]->categories->category[1];

$books = simplexml_load_file('books.xml');
echo $books->book[0]->categories->category[1];

Assuming that $first_name and $family_name are valid strings, which statement is invalid?

echo $first_name. ' '. $family_name;
echo $first_name, ' ', $family_name;
print $first_name. ' '. $family_name;
print $first_name, ' ', $family_name;

What is the job of the controller as a component in MVC?

The controller presents content through the user interface, after communicating directly with the database.
The controller handles data passed to it by the view, and also passes data to the view. It interprets data sent by the view and disperses that data to the appropriate models awaiting results to pass back to the view.
The controller is a mechanism that allows you to create reusable code in languages such as PHP, where multiple inheritance is not supported.
The controller handles specific tasks related to a specific area of functionality, handles business logic related to the results, and communicates directly with the database.

Imagine a web application, built following an MVC architecture, that contains a quiz and a button to score it. When the user presses the Score button, which component should handle the request?


When can you omit the semicolon at the end of a statement (command)?

You can omit semicolons as long as each statement is on a separate line. PHP inserts them automatically, just like JavaScript.
You can omit semicolons if the script begins with declare(strict_types=0).
You can omit semicolons after the final statement in a PHP block.
Never. PHP statements must always be followed by a semicolon.

What PHP control structure is used inside of a loop to skip the rest of the current loop's code and go back to the start of the loop for the next iteration?


Where is PHP code executed?

on a web server
in the memory of the computer viewing the webpage
in the virtual machine
in the client's browser

Your site must allow uploading of large files. What might you need to do?

Change the upload_max_filesize configuration parameter.
Be sure to use chunked transfer encoding.
Make sure the user has the proper permissions.
Keep a count of upload file sizes and log them.

Which line could you NOT use to comment out "Space: the final frontier"?

*/ Space: the final frontier /*
/* Space: the final frontier */
# Space: the final frontier
// Space: the final frontier

Which is the correct format for adding a comment to a PHP script?

/* This is a comment */
// This is a comment
all of these answers
# This is a comment

What might be the cause of the error "Cannot modify header information - headers already sent"?

You are most likely missing a semicolon.
You are trying use a key on an array that does not exist.
Some HTML is being sent before a header() command that you're using for a redirect.
You are trying to modify a value that is private.

When should you employ the POST method over the GET method for submitting data from a form?

when you want the data to be cached
when efficiency is important
when the data in the form may be sensitive
when you want to use your browser to help with debugging

Assuming the Horse class exists, which is a valid example of inheritance in PHP?

class Unicorn implements Horse {}
class Horse inherits Unicorn {}
class Alicorn imports Pegasus, Unicorn {}
class Pegasus extends Horse {}

Using a for loop, how would you write PHP code to count backward from 10 to 1, in that order?

1 <?
2 for ($i = 10; $i > 0; $i++){
3 print "$i <br />\n";
4 } // end for loop’’’
5 ?>

1 <?
2 $i = 10;
3 while($i>=0) {
4 echo $i;
5 $i--;
6 }
7 ?>

1 <?
2 for ($i = 1; $i <= 10; $i++) {
3 echo $i;
4 }
5 ?>

1 <?
2 for ($i = 10; $i > 0; $i--){
3 print "$i <br />\n";
4 } // end for loop
5 ?>

A form to subscribe to a newsletter is submitted using the POST method. The form has only one field: an input text field named "email". How would you check if the field is empty and, if it is, print "The email cannot be empty"?

1 if(empty($POST('email'))) {
2 echo "The email cannot be empty";
3 }

1 if(empty($_POST['email'])) {
2 echo "The email cannot be empty";
3 }

1 if(isset($email)) {
2 echo "The email cannot be empty";
3 }

1 if(empty($_GET['email'])) {
2 echo "The email cannot be empty";
3 }

 LinkedIn PHP Assessment Test 2021