PHP Test Upwork

What is the procedural style of associative array?

$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", .$row["Name"], $row[0]);

If you are given two dates in this form:
Start Date: 2007-03-24
End Date: 2009-06-26
Which code snippet finds the difference between these two in the following form:
2 years, 3 months and 2 days
PHP > 5.3

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date2->diff($date1);
echo "difference " . $interval->days . " days ";

$date1 = "2008-11-01 22:45:00";
$date2 = "2009-12-04 13:44:01";
$diff = abs(strtotime($date2) - strtotime($date1));
$years   = floor($diff / (365*60*60*24));
$months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
$minuts  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);

 Use CodeIgniter timespan() function

Which of the following is the correct way to add 1 to the $count variable?

++count;
count++;
$count++;
$count=+1;

Which of the following statement is not correct?

isset() is faster, but it's not the same as array_key_exists().
array_key_exists() purely checks if the key exists, even if the value is NULL.
isset() will return false if the key exist and value is NULL
None of the above

Which of the following is the correct way to create an array in PHP?

$animals = array(Cat, Dog, Horse);
$animals = array("Cat", "Dog", "Horse");
$animals = array["Cat", "Dog", "Horse"];
$animals = "Cat", "Dog", "Horse";

Which of the following is not a valid DOM method in PHP?

loadXMLFile()
loadXML()
loadHTMLFile()
loadHTML()

Given the following array:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
Which one of the following will print 2?

echo array_search('green', $array);
echo in_array('green', $array);
echo array_key_exists(2, $array);
echo array_search('red',$array);

Which of the following are not considered Boolean false?
Note: There may be more than one right answer.

FALSE
0
"0"
"FALSE"
1
NULL

What is the correct way to send an SMTP (Simple Mail Transfer Protocol) email using PHP?

s.sendmail($EmailAddress, [$MessageBody], msg.as_string())
sendmail($EmailAddress, "Subject", $MessageBody);
mail($EmailAddress, "Subject", $MessageBody);
<a href="mailto:$EmailAddress">$MessageBody</a>

What will be the output of the following code?
<?php
var_dump (3*4);
?>

int(3*4)
int(12)
3*4
12
None of the above

What will be the output of the following code?
<?
$a = (1 << 0); $b = (1 << 1); echo ($b | $a) << 2 ;
?>

1
2
3
4
8
12
 Syntax error

What will be the output of the following code?
<?php
echo 30 * 5 . 7;
?>

150 . 7
1507
150.7
Integers can't be concatenated.
An error will be thrown.

What will be the output of the following code?
<?
echo 5 * 6 / 2 + 2 * 3;
?>

1
20
21
23
34

What is the output of the following code?
<?php
  $string1 = "abcdefg";
  $string2 = "abcfghi";
  $position = strspn($string1 ^ $string2, "\0");
  echo $position;
?>

1
2
3
4

What will be the output of the following code?
$var = 10;
function fn()
{
   $var = 20;
   return $var;
}
fn();
echo $var;

10
20
Undefined Variable
Syntax Error

What is the correct syntax of mail() function in PHP?

mail($to,$subject,$message,$headers)
mail($from,$to,$subject,$message)
mail($to,$from,$subject,$message)
mail($to,$from,$message,$headers)

What will happen if a fatal error was thrown in your PHP program?

The PHP program will stop executing at the point where the error occurred.
The PHP program will show a warning message and program will continue executing.
Since PHP is a scripting language so it can not throw a fatal error.
Nothing will happen.

Which of these is not a valid PHP XML API?

libxml_clear_errors()
libXMLError()
libxml_get_errors()
libxml_use_internal_errors()

Which of the following file modes is used to write into a file at the end of the existing content, and create the file if the file does not exist?

r+
w+   
a
x

Which of the following is false about cURL?

cURL can be used to send plain text data to a remote server.
cURL can be used to send both text as well as files using a single request.
cURL can be used to send files to a remote server.
Files cannot be sent using cURL.

Which of the following will produce a value of "83" as its output?

echo intval("0123", 8);
echo (int) 083
echo (int) 123;
echo intval("0123");

Which of the following variable declarations within a class is invalid in PHP?

private $type = 'moderate';
internal $term = 3;
public $amnt = '500';
protected $name = 'Quantas Private Limited';

With regards to the "static" keyword in PHP, which of the following statements is false?

The $this variable can be used inside any static method.
Static properties may only be initialized using a literal or a constant.
A property declared as static can not be accessed with an instantiated class object.
A static variable or method can be accessed without requiring instantiation of the class.

Which of the following will store order number (34) in an ‘OrderCookie’?

setcookie(“OrderCookie”,34);
makeCookie(“OrderCookie”,34);
Cookie(“OrderCookie”,34);
OrderCookie(34);

Which of the following methods is used to check if an array is associative or numeric?

is_Assoc().
isAssoc().
is_assoc()
None of the above.

Which MIME type needs to be used to send an attachment in mail?

text/html
text/plain
application/mixed
multipart/mixed

You can extend the exception  class, but you can not override any of the preceding methods because they are declared as:

protected
final
static
private

Which function can be used to determine if a file exists? (choose all that apply)
Note: There may be more than one right answer.

is_readable()
file_exists()
feof()
is_file_exists()

Which is true about the curl_setopt() API?

PHP does not provide such an API.
It sets multiple options for a cURL transfer.
It executes the curl command.
It sets one option for a cURL transfer.

What is the fastest way to insert an item $item into the specified position $position of the array $array?

array_insert()
array_splice()
array_merge() and array_slice()
PHP does not have any built-in function that can do this: the source array will have to be copied, and $item inserted in to the required position:
$n = 0;
foreach ($array as $key => $val) {
    if ($n == $position) {
        $target[] = $item;
    }
    ++$n;
    $target[$key] = $val;
}

Which code snippet outputs a random string?

<?php
    Function RandomString()
    {
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
    $randstring = '';
    for ($i = 0; $i < 10; $i++)
        {
            $randstring = $characters[rand(0, strlen($characters))];
        }
    return $randstring;
    }
    RandomString();
    echo $randstring; ?>

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function generateRandomString($length = 15)
{
    return substr(sha1(rand()), 0, 0);
}

function RandomString($length) {
    $keys = array_merge(range(0,9), range('a', 'z'));
    for($i=0; $i < $length; $i++) {
        $key = $keys[array_rand($keys)];
    }
    return $key;
}

Which of the following is the right MIME to use as a Content Type for JSON data?

text/x-json
text/javascript
application/json
application/x-javascript

Which of the following statements is incorrect, with regards to inheritance in PHP?

A class can only have a single parent, i.e. it cannot extend more than one class.
A class can both extend another class as well as implement an interface.
A class can implement more than one interface.
A class can extend more than one class.

Which is the best approach to parse HTML and extract structured information from it?

Use an existing LibXML based library like DOM or phpQuery.
String searching and extraction.
Use an XML parser (as simpleXML) and XPath queries if available.
Use specific regular expressions.

What is the correct way to read-in multiple values from an array?

$x,$y,$z = array(7,8,9);
($x,$y,$z) = array(7,8,9);
array($x,$y,$z) = array(7,8,9);
list($x,$y,$z) = array(7,8,9);

Which of the following is the correct way to convert a variable from a string to an integer?

$number_variable = int_val $string_variable;
$number_variable = (int_val)$string_variable;
$number_variable = int($string_variable);
$number_variable = (int)$string_variable;

What is true about get_defined_vars() function?

It returns the array of all the defined variables.
It returns the array of all the defined variables of a function.
It returns all the $_POST variables only.
It returns all the $_GET variables only

Which of the following will return the complete URL of the requested PHP page?

apache_getenv(«HTTP_HOST»)
$_SERVER[‘HTTP_HOST’]
$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’];
$_SERVER[‘REQUEST_URI’];

Which of the following will not give the correct date and time in PHP?

date(«Y-m-d H:i:s»)
date(«y-m-d H:i:s»)
date(«f, j Y H:i:s»)
date(«F, j Y H:i:s»)

Which directive determines how the session information will be stored?

save_data
session_save
session.save_data
session.save_handler

What is the output of the following code?
<?php
echo «<pre>»;
$array1 = array(
«1»=>»a»,
«2»=>»b»,
«3»=>»c»
);
$array = array_flip($array1);
print_r($array);
echo «</pre>»;
?>

 Array
(
[1] => a
[2] => b
[3] => c
)

Array
(
[a] => 1
[b] => 2
[c] => 3
)

 Array
(
[0] => c
[1] => b
[2] => a
)

 Array
(
[0] => 1
[1] => 2
[2] => 3
)

Which is the best way to automatically deploy a PHP website using git push?

It is not possible.
You should have two copies on your server. A bare copy, that you can push/pull from, to which you would push your changes to when you are done. Then you would clone this into your web directory and set up a cronjob to update git pull from your web directory every day or couple of days.
Developing from scratch a custom deployment script to manage all the aspects.
Copy over your git directory to your web server. On your local copy, modify your .git/config file and add your web server as a remote. On the server, replace .git/hooks/post-update with an existing script to process the rest of the workflow.
Make the script executable.

Which method is used to sort multidimensional arrays in PHP?

krsort
rsort
array_multisort
usort

Which of the following code snippets has the most appropriate headers to force the browser to download a CSV file?

header(«Content-type: text/csv»);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);

header(‘Content-Type: application/download’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);

header(‘Content-Type: application/csv’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);

header(‘Content-Type: application/octet-stream’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);

Which of the following is false with respect to Bridge pattern in PHP?

Bridge is designed up-front to let the abstraction and the implementation vary independently.
Decouple an abstraction from its implementation so that the two can vary independently.
Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy.
Use bridge when you do not want to share an implementation among multiple objects.

What will be the output of the following code?
<?php
$x = 10;
if ($x == 10):
?>
<p>Hi!</p>
<?php else:?>
<p>Bye!</p>
<?php endif; ?>

Hi!
Bye!
The code will throw an error, as there is no curly brace after the if statement, and it has a misplaced colon(:).
The code will throw an error, as there is no curly brace after the else statement, and it has a misplaced colon(:).

What is the output of the following code?
<?php
$a = 123;
$b = «123»;
if ($a == $b) echo ‘A’;
if ($a === $b) echo ‘B’;
?>

<empty output>
A
B
AB

What will be the output of the following code?
<?php
$xmlFile = «<root><css><element><csstag><title>background-color</title><value>#FFF</value></csstag><csstag><title>color</title><value>#333</value></csstag><csstag><title>font-family</title><value>Verdana, Geneva, sans-serif</value></csstag></element></css></root>»;
$xml = simplexml_load_string($xmlFile);
foreach($xml->css as $css) {
echo (string) $css->element[‘id’].»{«;
foreach($xml->css->element->csstag as $tag) {
$temp = $tag->title.»: «.$tag->value.»;»;
echo $temp;
}
echo «}»;
}
?>

syntax error
background-color: #FFF;color: #333;font-family: Verdana, Geneva, sans-serif;
parse error;
{background-color: #FFF;color: #333;font-family: Verdana, Geneva, sans-serif;}

Which of the following is true with respect to Flyweight design pattern in PHP?

All the methods of the class should be private.
This pattern is used when you need only a small number of instances of same type.
Using this pattern consumes a lot of memory.
Instances of a class which are identical are shared in an implementation instead of creating a new instance of that class for every instance.

Which of the following is incorrect way to take a PHP variable named $name and reassign it to a javascript variable var name?

<script>
var name = «<?php echo $name;?>»;
</script>
<script>
var name =<?php echo $name;?>;
</script>
<script>
var name = <?php echo json_encode($name);?>;
</script>
<script>
var name = «<?php echo addslashes($name);?>»;
</script>

What is the output of the following code?
<?php
function y($v) {
echo $v;
}
$w = «y»;
$w(«z»);
$w = «x»;
?>

x
y
z
<error>

Which of the following is used to send mail in PHP?

send_mail(to,subject,message,headers,parameters);
mail(to,subject,message,headers,parameters);
mail::(to,subject,message,headers,parameters);
mail_to(to,subject,message,headers,parameters);

Placing the ____ symbol before a function tells PHP to suppress any errors generated by that function.

!
@
#
$

Which statement is not correct?
$x = null;

empty($x) return TRUE
is_null($x) return FALSE
isset($x) return FALSE
None of the above

Which of these is not a valid SimpleXML Parser method?

simplexml_import_dom()
simplexml_import_sax()
simplexml_load_file()
simplexml_load_string()

The _________ statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the statement. Check all that apply.
Note: There may be more than one right answer.

require
include
get
add

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
What will be the output of above code?

HelloWorld!BeautifulDay!
'Hello','World!','Beautiful','Day!'
Hello World! Beautiful Day!
No output

Which of the following are valid MySQLi Configuration Options? (choose all that apply)
Note: There may be more than one right answer.

mysqli.allow_persistent
mysqli.rollback_on_cached_size
mysqli.default_port
mysqli.default_socket

Which of the following functions is not related to garbage collection in PHP?

gc_collect_cycles()
gc_cycles()
gc_disable()
gc_enable()

How can you connect with a MySQL Server in PHP?

database_connect(server, username, password)
mysql_connect(host, username, password)
mysql(server, username, password)
connect(server, username, password)

<?php
$string = 'i wish i had 3three some capitalization';
echo ucwords($string);
?>
What will be the output of above code?

I wish i had 3three some capitalization
i wish i had 3three some capitalization
I Wish I Had 3three Some Capitalization
No output

What is wrong with the following code?
<?php
curl_setopt($ch, CURLOPT_URL, «http://www.example.com/»);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>

There is nothing wrong with the code.
The cURL resource $ch has not been created using the curl_init() method.
The $ch variable needs to be initialized as $ch=null;.
The code will cause a parse error

PHP ____ are used to validate and sanitize external input.

Cookies
Filters
Exceptions
Files

<?php
var_dump( floor(3.74) );
?>
What will be the output of the code?

4
3
float(3)
floor(3)

What will be the output of the following code?
class Person
{
    protected $name;  
    public function __construct($name) {
        $this->name = $name;
    }
    public function getName() {
        return $this->name;
    }
}
$person = new Person("Foo");
echo $person->getName();

Nothing will be printed on-screen.
Foo
Syntax error on line $this->name=$name
Fatal error on line $this->name=$name

Where can protected property or method be accessed?

it can only be accessed within the class itself.
it can be accessed outside of the class.
it can only be accessed within the class itself or in descendant classes.
It can not be accessed anywhere.

Which expression will not produce ‘abcdef’ as a result provided if $var1=’abc’ and $var2=’def’?

$var1 + $var2
"{$var1}{$var2}"
$var1.$var2
implode('', array($var1,$var2))

PHP currently offers the following functions for searching strings using POSIX-style regular expressions? (choose all that apply)
Note: There may be more than one right answer.

sql_regcase()
eragi_replace()
ereg_replace()
spliti()
erag()

Which function is used to destroy a variable or object?

destroy()
clear()
unset()
reset()

Which of the following is not a valid cURL parameter in PHP?

CURLOPT_RETURNTRANSFER
CURLOPT_GET
CURLOPT_POST
CURLOPT_POSTFIELDS

<?php
$x = 1;
while ($x <= 3){
  echo "$x, ";
  $x++;
}
?>
What will be the output of above code?

1
1, 2, 3,
1, 2, 3
No output

Which function is used to calculate the amount of memory allocated to a PHP script?

emalloc()
get_total_memory_usage()
get_memory_usage()
memory_get_usage()

Which of the following data types are supported in PHP? Check all the apply.
Note: There may be more than one right answer.

Float
Boolean
NULL
Text

Which statement is incorrect with respect to "!==" and "==!"?

There is no such operator as ==! in PHP.
==! is a combination of 2 operators, == and !. It is same as == (!$var)
There is no such operator as !== in PHP.
!== returns true if left hand side operand is not identical to right hand side operand.

Which of the following is the correct way to create a function in PHP?

new_function myFunction()
function myFunction()
create myFunction()
new myFunction()

How would you create enums in PHP?

Use Enum class provided by PHP.
Use SplEnum which gives the ability to emulate and create enumeration objects natively in PHP
Enums can not be created in PHP.
Use typedef to create enums in PHP.

The following code would:
$reflFunc = new ReflectionFunction('func');
print $reflFunc->getFileName();

Give the path of 'func' function
Create clone of 'func' function
None
Undefined function error

How to remove whitespace from the beginning and end of $string variable?

cut($string);
removeSpace($string);
shorten($string);
trim($string);

__________ is a PHP super global variable which holds information about headers, paths, and script locations.

$_REQUEST
$_SERVER
$_INFO
$_GET

What does "===" operator do in PHP?

Assigns the value on the right to the variable on the left.
Checks if the left and right values are equal and are of same type.
Checks if the left and right values are equal but not identical.
Checks if the left and right values are not equal.

How can short tags be enabled in PHP?

Set the value of short_open_tag=on in the php.ini file and restart the web server.
Set the value of short_tag=on in the php.ini file and restart the web server.
Set the value of short_tags=on in the php.ini file.
None of the above.

'Paamayim Nekudotayim' is also called :

Exponentiation operator
Scope resolution operator
Modulus operator
Logical operators

Which of the following function is used to get length of a string?

size()
strlen()
length()
None of the above

Which of these is not a valid PHP XML DOM method?

getElementsByTagName
removeChild()
getElementsById()
appendChild()

How do you check if a variable is empty?

isset($variable)
empty($variable)
is_empty($variable)
no_value($variable)

What is $_REQUEST?

Contains a reference for all variables, global or otherwise, in the script.
Includes all variables submitted through HTTP POST, such as an HTML form with action="post".
Includes all variables provided by $_GET, $_POST, and $_COOKIE.
A collection of variables about the server environment.

Pick the correct PHP function to rewind the internal array pointer.

last()
before()
prev()
previous()

By which delimiters are PHP scripts enclosed?

<script.../script>
<?php>...</?>
<?php...?>
<&>...</&>

Which of the following method is triggered when invoking inaccessible methods in an object context?

__call()
__callStatic()
_call()
_callStatic()

Which operator is used to access static properties or methods of a class?

.
:
->
:

What of the following variables are correct Superglobals ?

$_SERVER
$_GET
$_TRACE
$_COOKIE

$_SERVER
$_GET
$_POST
$_COOKIE

$_SERVER
$_GET
$_PUT
$_COOKIE

$_SERVER
$_GET
$_POST
$_DELETE

PHP Test Upwork 2019{jcomments off}