linkedin-skill-assessments-quizzes

PHP

Q1. What does this code output?

echo 76 <=> '76 trombones';

Both sides of the “spaceship” are equal, so the answer is 0. PHP will convert ‘76 trombones’ to 76 in this context, as the string starts with ‘76’. Try it! For php 8.0 and forward the answer is [x] -1, for previous versions the answer is [x] 0. PHP 8 changed the way non-strict comparison between numbers and non-numeric strings work.

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

Q3. What does this script do?

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    $emailErr = "Please re-enter valid email";
}

Q4. 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 ?>

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

Q6. All variables in PHP start with which symbol?

Q7. What is a key difference between GET and POST?

Q8. 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

Q9. Which are valid PHP error handling keywords?

Q10. Which value equates to true?

Q11. What is missing from this code, which is supposed to create a test cookies?

$string_name = "testcookie";
$string_value = "This is a test cookie";
$expiry_info = info()+259200;
$string_domain = "localhost.localdomain";

Q12. What is the value of $total in this calculation?

$total = 2 + 5 * 20 - 6 / 3

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

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

Q15. What is the best way to explain what this script does?

if (!$_SESSION['myusername'])
{
  header('locaton: /login.php');
  exit;
}

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

Q17. PHP supports multiple types of loops. If you wanted to loop through a block of code if and as long a specified condition is true, which type of loop would you use?

Q18. The ignore_user_abort( ) function sets whether a client disconnect should abort a script execution. In what scenario would you, as a web developer, use this function?

Q19. The PHP function array_reduce() takes a callback function that accepts a value carried over each iteration and the current item in the array, and reduces an array to a single value. Which code sample will sum and output the values in the provided array?

  <?php
  echo array_reduce([1, 2, 5, 10, 11], function ($item, $carry) {
      $carry = $carry + $item;
  });
?>
  <?php
  echo array_reduce([1, 2, 5, 10, 11], function ($carry, $item) {
      return $carry = $item + $item;
  });
?>
  <?php
  array_reduce([11 2, 5, 10, 11], function ($item, $carry) {
      echo $carry + $item;
  });
?>
  <?php
  echo array_reduce([1, 2, 5, 10, 11], function ($carry, $item) {
      return $carry += $item;
  });
?>

Q20. Which PHP script uses a constructor to display the string “Winter is almost over!”?

  class MyClass {
  public function _construct()
  {
  echo 'Winter is almost over!'."\n";
  }
  }
  $userclass = new MyClass;
  class MyClass {
  public function _construct()
  {
  echo 'Winter is almost over!.."\n";
  }
  }
  $userclass = new MyClass;
  class MyClass {
  public function _construct()
  {
  echo 'Winter is almost over!.."\n";
  }
  }
  $userclass = new MyClass;
  class MyClass {
  public function _construct()
  {
  echo 'Winter is almost over!'."n";
  }
  }
  $userclass = MyClass;

Q21. How might you troubleshoot a “call to undefined function” error?

Q22. Which line could you NOT use to comment out “Space: the final frontier”?

Q23. What displays in a browser when the following code is written? <?php echo "How much are the bananas?"?>

Q24. Which operator would you use to find the remainder after division?

Q25. What is the significance of the three dots in this function signature?

function process(...$vals) {
    // do some processing
}

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

Q27. Both triple === and double == can be used to variables in php. If you want to hear that string “33” and the number 33 are equal, you would use . If you want to check if an array contains a particular string value at a particular index, you would use _

Q28. Your php page is unexpectedly rendering as totally blank. Which step will shed light on the problem?

Q29. Which is the way to create an array of “seasons”?

seasons=array(
    1=>'spring',
    2=>'summer',
    3=>'autumn',
    4=>'winter',
);

Q30. Both self and this are keywords that can be used to refer to member variables of an enclosing class. The difference is that $this->member should be used for members and self::$member should be used for members

Q31. What will this code print?

$mathe=array('archi','euler','pythagoras');
array_push($mathe,'hypatia');
array_push($mathe,'fibonacci');
array_pop($mathe);
echo array_pop($mathe);
echo sizeof($mathe);

Q32. You are using the following code to find a users band, but it is returning false. Which step(s) would solve the problem?

isset ($_GET['fav_band'])

Q33. Which code would you use to print all the elements in an array called $cupcakes?

Q34. What is the cause of ‘Cannot modify header information - headers already sent’?

Q35. Which php control structure is used inside a loop to skip the rest of the current loops code and go back to the start of the loop for the next iteration

Q36. The php not operator is !. Given the snippet, is there an out put and what is it?

Q37. You want to list the modules available in your PHP installation. What command should you run?

Q38. For the HTML form below, what is the correct functioning script that checks the input “mail” to be sure it is filled before proceeding?

if (!empty($_POST["mail"])) {
echo "Yes, mail is set";
} else {
echo "No, mail is not set";
} (correct)

Q39. What is the value of $result in this calculation?

$result = 25 % 6;

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

Q41. Why does this code trigger an error?

$string = 'Shylock in a Shakespeare's "Merchant of Venice" demands his pound of flesh.';

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

Q44. Which code snippet demonstrates encapsulation?

  class Cow extends Animal {
      private $milk;
  }
  class Cow {
      public $milk;
  }
  $daisy = new Cow();
  $daisy->milk = "creamy";
  class Cow {
      public $milk;
      function getMilk() {`
          return $this->milk;
      }
  }
  class Cow {
      private $milk;
      public function getMilk() {
          return $this->milk;
      }
  }

Q45. The following XML document is in books.xml. Which code will output “Historical”?

<books>
    <book>
        <title>A Tale of Two Cities</title>
        <author>Charles Dickens</author>
        <categories>
            <category>Classics</category>
            <category>Historical</category>
        </categories>
    </book>
    <book>
        <title>Then There Were None</title>
        <author>Agatha Christies</author>
        <categories>
            <category>Mystery</category>
        </categories>
    </book>
</books>
  $books = simplexml_load_string('books.xml');
  echo $books->book[0]->categories->category[1];
  $books = simplexml_load_file('books.xml');
  echo $books->book[0]->categories->category[1];
  $books = SimpleXMLElement('books.xml');
  echo $books->book[0]->categories->category[1];
  $books = SimpleXML('books.xml');
  echo $books->book[0]->categories->category[1];

Q46. When it comes to the value of a variable, what is the difference between NULL and empty?

Q47. What would be a good name for this function?

function doStuff($haystack, $needle) {
      $length = strlen($needle)
      if (substr($haystack, 0, $length) == $needle)
        return true;
      else
        return false;
}

Q48. If you want to pass a formfield to another page when a button is clicked, you should use the . If you want to store information across multiple pages, you should use the ?

Q49. You are using the following code to decide if a button is clicked, but it is never returning true. Which step is most likely to shed light on the problem?

isset($_POST['submit'])

Q50. Why should you follow a PSR standard?

Q51. What are getters and setters?

  report_errors = E_ALL
  display_errors = On
  error_reporting = E_ALL
  display_errors = On
  error_reporting = E_ALL & ~E_NOTICE
  display_errors = Off
  error_reporting = E_ALL & ~E_NOTICE
  display_errors = On

Q53. Which PHP variable name is invalid?

Q54. Which command will extract the domain suffix (“com”) from the string $string = "https://cat-bounce.com";?

Q55. Where is PHP code executed?

Q56. Which is not a valid magic constant?

Reference

Q57. What below script will print?

  if( 1 == true){
        echo "1";
  }

  if( 1 === true){
      echo "2";
  }

  if("php" == true){
      echo "3";
  }

  if("php" === false){
      echo "4";
  }

Q58. When should this php script be used?

$secret_word = 'if i ate spinach';
setcookie('login', $_REQUEST['username']. ','. md5($_REQUEST['username'].$secret_word));

Q59. A PHP “variable variable” takes the value of a variable and treats that as the name of a variable. For example, if $var is a variable then $$var is a variable variable whose name is the value of $var. Which script produces the output below, using variable variables?

Cat
Dog
Dog
  $name = "Cat";
  $name = "Dog";
  echo $name . "<br/>";
  echo $$name . "<br/>";
  echo $Dog;
  $name = "Cat";
  $$name = "Dog";
  echo $name . "<br/>";
  echo $$name . "<br/>";
  echo $Dog;
  $name = "Cat";
  $$name = "Dog";
  echo $name . "<br/>";
  echo $$name . "<br/>";
  echo $Cat;
  $name = "Cat";
  $$name = "Dog";
  echo $name . "<br/>";
  echo $name . "<br/>";
  echo $Cat;

Q60. Imagine a web application, built following a 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?

Q61. Which script might be used to continue a user’s search for music, across different webpages?

  <?php
      start_session();
      $music = $_SESSION['music'];
  ?>
  <?php
      session_start();
      $music = $SESSION['music'];
  ?>
  <?php
      start_session();
      $music =$session['music'];
  ?>
  <?php
      session_start();
      $music = $_SESSION['music'];
  ?>

Q62. Which PHP script finds the earliest and latest dates from an array?

  <?php
  $dates = array('2018-02-01', '2017-02-02', '2015-02-03');
  echo "Latest Date: ". max($dates)."\n";
  echo "Earliest Date: ". min($dates)."\n";
  ?>
  <?php
  $dates = array('2018-02-01', '2017-02-02', '2015-02-03');
  echo "Latest Date: ". min($dates)."\n";
  echo "Earliest Date: ". max($dates)."\n";
  ?>
  <?php
  $dates = array('2018-02-01', '2017-02-02', '2015-02-03');
  echo "Latest Date: ". ($dates)."\n";
  echo "Earliest Date: ". ($dates)."\n";
  ?>
  <?php
  $dates = array('2018-02-01', '2017-02-02', '2015-02-03');
  echo "Latest Date: " max($dates)."\n";
  echo "Earliest Date: " min($dates)."\n";
  ?>

Q63. What is the resulting output of this for statement?

$kilometers = 1;
for (;;) {
    if ($kilometers > 5) break;
       echo "$kilometers kilometers = ".$kilometers*0.62140. " miles. <br />";
    $kilometers++;
}
  kilometers = 0.6214 miles.
  kilometers = 1.2428 miles.
  kilometers = 1.8642 miles.
  kilometers = 2.4856 miles.
  kilometers = 3.107 miles.
  kilometers = 0.6214 miles.
  kilometers = 1.2428 miles.
  kilometers = 1.8642 miles
  kilometers = 2.4856 miles.
  kilometers = 3.107 miles.
  kilometers = 3.7284 miles.
  kilometers = 1.2428 miles.
  kilometers = 1.8642 miles.
  kilometers = 2.4856 miles.
  kilometers = 3.107 miles.

Q64. In PHP 7, What is the correct way to import multiple classes from namespace in a single declaration ?

Q65. Which is the most complete list of data types that PHP supports?

reference

Q66. What type of computer language is PHP?

reference

Q67. Which superglobal variable holds information about headers, paths, and script locations?

reference

Q68. Describe what happens if you run this code in a testing environment

$capitals = ['UK' => 'London', 'France' => 'Paris'];
echo "$capitals['france'] is the capital of France.";

Also, ‘france’ key must be capitalized!

Q69. DRY (Don’t Repeat Yourself) is a principle of software development aimed at reducing repetition of software patterns. Which choice is not a way to write DRYer code with PHP?

Q70. Which code will return the IP address of the client?

Both 2 and 4 are correct!

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

Q72. What is the output of this script?

$my_text = 'The quick grey [squirrel].';
preg_match('#\[(.*?)\]#', $my_text, $match);
print $match[1]."\n";

Q73. What is the output of this script?

$fruits = ['apple', 'orange', 'pear', 'mango', 'papaya']; $i = 0; echo $fruits[$i+=3];

Q74. What are some of the main types of errors in PHP?

Q75. What is the correct way to include the file gravy.php in the middle of HTML code?

Q76. Which two functions can sanitize text and validate text formats?

Q78. 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?

Q79. Create an associative array using $array1 as the keys and $array2 as the values

$array1 = ['country', 'capital', 'language']; $array2 = ['France', 'Paris', 'French'];

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

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

1 seems correct, but the question asks for “day”, not day of the week. Twelfth Night is the “06” day of January, 2019.

Q82. Which loop displays all numbers from 1 to 10 inclusive?

Q83. Which are types of control structures in PHP?

reference

Q84. Which function can you use in error handling to stop the execution of a script and is equivalent to exit()?

Q85. Is the output of this code in descending order, shown vertically, and with spaces between numbers? And what is the output?

$numbers = array(4,6,2,22,11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++){
    echo $numbers[$x];
    echo "<br />";
    }

Q86. Which is not true of the toString() in PHP?

Q87. What is a generator and how is it used in PHP?

Q88. What is the best description of what this script is/does?

if( isset($user_info['url']) ) {
  $_SESSION["loggedIn"] = true;
  $_SESSION["username"] = $myusername;
  header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
} else {
  header("Location: error.htm");
}

Q89. What is the output of this code?

echo 5 % 0.75;

Q90. Can you extend a final defined class?

Q91. How can you test if a checkbox is set?

Actually both are correct, option 3 is actually testing if a checkbox is not set

Q92. A form to subscrive 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”?

if(empty($_POST['email'])) {
    echo "The email cannot be empty";
}
if(empty($_GET['email'])) {
    echo "The email cannot be empty";
}
if(empty($_POST('email'))) {
    echo "The email cannot be empty";
}
if(isset($email)) {
    echo "The email cannot be empty";
}

Q93. What is the PHP fatal error type?

  1. reference1
  2. reference2

Q94. Which script properly validates the IP address given?

$valid = ip2long($ip) !== false;
$ip_address = "164.12.2540.1";
if(filter_var($ip_address, FILTER_VALIDATE_IP)){
  echo "$ip_address is a valid IP address";
} else {
  echo "$ip_address is not a valid IP address";
}
$ip_address = "164.12.2540.1";
if(validate_ip($ip_address)){
  echo "$ip_address is a valid IP address";
} else {
  echo "$ip_address is not a valid IP address";
}
$ip_address = "164.12.2540.1"
echo is_valid($ip_address, VALIDATE_IP);

Q95. What is the output of this code?

    $i = 0;
    while($i < 6) {
    if($i++ == 3) break;
    }
    echo "loop stopped at $i by break statement";
    $dof->setTitle("Spot");
    $cat->setTitle("Mimi");
    $horse-?setTitle("Trigger");
    $dog->setPrice(10);
    $cat->setPrice(15);
    $horse->setPrice(7);
    print_r($cat);

Q97. Given the associative array below, wich PHP code determines wich element(s) of the array is/are apple?

$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
while ($fruit_name = current($array)) {
    if ($fruitname == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple')
        echo key($array).'<br />';
    }
    next($array);
}
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }

Q98. What does this code return?

Q98. What does this code print?

class Smurf {

  public $name = "Papa Smurf";

  public function __construct($name) {
    $this->name = $name;
  }

  public function set_name($name) {
    $name = $name;
  }
}

$smurf = new Smurf("Smurfette");
$smurf->set_name("Handy Smurf");
echo $smurf->name;

Q99. You have an online form with a file input field called “image” for uploading files. Assuming the path to the upload directory is $path, which code should you use to make sure the file is uploaded from your form to the correct location?

if ($_FILES['image']['error'] === 0) {
      move_uploaded_file($_FILES)['image']['temp_name'],
          $path . $_FILES['image']['name']);
 )
if ($_FILES['image']['error'] === false) {
      move_uploaded_file($_FILES)['image']['temp_name'],
          $path . $_FILES['image']['name']);
 )
if ($_FILES['image']['error'] == 0) {
      copy($_FILES)['image']['temp_name'],
          $path . $_FILES['image']['name']);
 )
if ($_FILES['image']['error'] == false) {
      upload_file($_FILES)['image']['temp_name'],
          $path . $_FILES['image']['name']);
 )

Q100. Which super global variable holds information about headers, paths, and script locations?

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

<?
for ($i=1; $i <= 10; $i++) {
    echo $i;
}
?>
<?
$i = 10;
while($i>=0) {
    echo $i;
    $i--;
}
?>
<?
    for($i = 10; $i > 0; $i++) {
        print "$i <br />\n";
    } // end for loop '''
?>
<?
    for($i = 10; $i > 0; $i--) {
        print "$i <br />\n";
    } // end for loop
?>

Q102. What is the output of this code?

function knights(){
return "a shrubbery";
}

if (knights())
printf "you are just and fair";
else
printf "NI!";

Q103. Which script defines the United States of America as a constant and prints this code?

Our country is United States of America Our country has a total of 50 states

define('country',"United States of America");
define('states',50);
echo "Our country is "country"<br>";
echo "Our country has a total of ".states." states";
define('country',"United States of America");
define('states',50);
echo "Our country is ".country."<br>";
echo "Our country has a total of ".states." states";
define(country,"United States of America");
define('states',50);
echo "Our country is ".country."<br>";
echo "Our country has a total of ".states." states";
define('country',"United States of America");
define('states','fifty');
$K = 'strval'; echo "Our {$K(Country)} has {$K(FIFTY)} states.";

Q104. What does this code output?

try{
echo "bodacious";
throw new Exception();
} catch (Exception $e) {
echo "egregious";
} finally {
echo "excellent";
}

Q105. Passing by reference is a way to pass a variable to a function and modify it inside the function, and have that modification stick when the variable is used outside the function. Which code correctly uses passing by reference to modify the variable for use outside the function?

Q106. What is the output of this script?

$believable = 'false';
$myth = 'The moon is made of green cheese';
$calc = 10**3+1;
if ($believable) {
    echo $myth;
}
else {
    echo $calc;
}

Explanation : ‘false’ evaluates to true since it is a string so the if condition is met.

Q107. 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?

Q108. What is the output of this code?

$x = "5";
$y = &$x;
$y = "2$y";
echo $x;

Q109. Which function is used to check if a file exists in PHP?

Q110. What does the following code output?

$array = array(1, 2, 3, 4, 5);
echo array_sum($array) / count($array);

Q111. Which of the following is NOT a valid way to start a PHP session?

Q112. What is the purpose of the ‘finally’ block in a try-catch-finally structure?

Q113. Which function would you use to remove HTML tags from a string?

Q114. What is the output of this code?

$str = "Hello";
$str[0] = "J";
echo $str;

Q115. Which of the following is NOT a magic method in PHP?

Q116. What does the ‘yield’ keyword do in PHP?

Q117. Which function would you use to get the ASCII value of a character?

Q118. What is the output of this code?

$a = array(1, 2, 3);
$b = array("one", "two", "three");
$c = array_combine($a, $b);
print_r($c);

Q119. Which of the following is NOT a valid PHP comparison operator?

Q120. What does the ‘static’ keyword do when used inside a function?

Q121. Which function would you use to get the current timestamp in PHP?

Q122. What is the output of this code?

$str = "abcdef";
echo substr($str, -2, 1);

Q123. Which of the following is NOT a valid way to comment in PHP?

Q124. What does the ‘instanceof’ operator do in PHP?

Q125. Which function would you use to check if a variable is an array?

Q126. What is the output of this code?

$x = 5;
$y = 10;
function myTest() {
    global $x, $y;
    $y = $x + $y;
}
myTest();
echo $y;

Q127. Which of the following is NOT a valid PHP array function?

Q128. What does the ‘final’ keyword do when used before a class declaration?

Q129. Which function would you use to get the length of a string in PHP?

Q130. What is the output of this code?

$a = "Hello";
$b = &$a;
$b = "World";
echo $a;