200-530 | 200-550 | 200-710
echo '1' . (print '2') + 3;
$a = 3; switch ($a) { case 1: echo 'one'; break; case 2: echo 'two'; break; default: echo 'four'; break; case 3: echo 'three'; break; }
$a = 'a'; $b = 'b'; echo isset($c) ? $a.$b.$c : ($c = 'c').'d';
echo "1" + 2 * "0x02";
1 ^ 2
echo "22" + "0.2", 23 . 1;
$first = "second"; $second = "first"; echo $$$first;
namespace MyFramework\DB; class MyClass { static function myName() { return __METHOD__; } } print MyClass::myName();
// test.php: include "MyString.php"; print ","; print strlen("Hello world!"); // MyString.php: namespace MyFramework\String; function strlen($str) { return \strlen($str)*2; // return double the string length } print strlen("Hello world!")
class C { public $ello = 'ello'; public $c; public $m; function __construct($y) { $this->c = static function($f) { // INSERT LINE OF CODE HERE }; $this->m = function() { return "h"; }; } } $x = new C("h"); $f = $x->c; echo $f($x->m);
function z($x) { return function ($y) use ($x) { return str_repeat($y, $x); }; } $a = z(2); $b = z(3); echo $a(3) . $b(2);
$f = function () { return "hello"; }; echo gettype($f);
class C { public $x = 1; function __construct() { ++$this->x; } function __invoke() { return ++$this->x; } function __toString() { return (string) --$this->x; } } $obj = new C(); echo $obj();
abstract class Base { protected function __construct() {} public static function create() { return new self(); // KEYWORD } abstract function action(); } class Item extends Base { public function action() { echo __CLASS__; } } $item = Item::create(); $item->action(); // outputs "Item"
class Base { protected static function whoami() { echo "Base "; } public static function whoareyou() { static::whoami(); } } class A extends Base { public static function test() { Base::whoareyou(); self::whoareyou(); parent::whoareyou(); A::whoareyou(); static::whoareyou(); } public static function whoami() { echo "A "; } } class B extends A { public static function whoami() { echo "B "; } } B::test();
class Test { public function __call($name, $args) { call_user_func_array(array('static', "test$name"), $args); } public function testS($l) { echo "$l,"; } } class Test2 extends Test { public function testS($l) { echo "$l,$l,"; } } $test = new Test2(); $test->S('A');
$obj = new MyObject(); array_walk($array, $obj);
# __invoke() # The __invoke() method gets called when the object is called as a function. # When you declare it, you say which arguments it should expect. Here's a trivially simple example: class Butterfly { public function __invoke() { echo "flutter"; } } # We can instantiate a Butterfly object, and then just use it like a function: $bob = new Butterfly(); $bob(); // flutterSource: http://lornajane.net/posts/2012/phps-magic-__invoke-method-and-the-callable-typehint
class Magic { protected $v = array("a" => 1, "b" => 2, "c" => 3); public function __get($v) { return $this->v[$v]; } } $m = new Magic(); $m->d[] = 4; echo $m->d[0];
Table data (table name "users" with primary key "id"): id name email ------- ----------- ------------------- 1 anna alpha@example.com 2 betty beta@example.org 3 clara gamma@example.net 5 sue sigma@example.infoPHP code (assume the PDO connection is correctly established):
$dsn = 'mysql:host=localhost;dbname=exam'; $user = 'username'; $pass = '********'; $pdo = new PDO($dsn, $user, $pass); $cmd = "SELECT * FROM users WHERE id = :id"; $stmt = $pdo->prepare($cmd); $id = 3; $stmt->bindParam('id', $id); $stmt->execute(); $stmt->bindColumn(3, $result); $row = $stmt->fetch(PDO::FETCH_BOUND);
Table data (table name "users" with primary key "id"): id name email ------- ----------- ------------------- 1 anna alpha@example.com 2 betty beta@example.org 3 clara gamma@example.net 5 sue sigma@example.infoPHP code (assume the PDO connection is correctly established):
$dsn = 'mysql:host=localhost;dbname=exam'; $user = 'username'; $pass = '********'; $pdo = new PDO($dsn, $user, $pass); try { $cmd = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)"; $stmt = $pdo->prepare($cmd); $stmt->bindValue('id', 1); $stmt->bindValue('name', 'anna'); $stmt->bindValue('email', 'alpha@example.com'); $stmt->execute(); echo "Success!"; } catch (PDOException $e) { echo "Failure!"; throw $e; }
Table data (table name "users" with primary key "id"): id name email ------- ----------- ------------------- 1 anna alpha@example.com 2 betty beta@example.org 3 clara gamma@example.net 5 sue sigma@example.infoPHP code (assume the PDO connection is correctly established):
$dsn = 'mysql:host=localhost;dbname=exam'; $user = 'username'; $pass = '********'; $pdo = new PDO($dsn, $user, $pass); $cmd = "SELECT name, email FROM users LIMIT 1"; $stmt = $pdo->prepare($cmd); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_BOTH); $row = $result[0];
Table data (table name "users" with primary key "id"): id name email ------- ----------- ------------------- 1 anna alpha@example.com 2 betty beta@example.org 3 clara gamma@example.net 5 sue sigma@example.infoPHP code (assume the PDO connection is correctly established):
$dsn = 'mysql:host=localhost;dbname=exam'; $user = 'username'; $pass = '********'; $pdo = new PDO($dsn, $user, $pass); try { $pdo->exec("INSERT INTO users (id, name, email) VALUES (6, 'bill', 'delta@example.com')"); $pdo->begin(); $pdo->exec("INSERT INTO users (id, name, email) VALUES (7, 'john', 'epsilon@example.com')"); throw new Exception(); } catch (Exception $e) { $pdo->rollBack(); }
$date1 = new DateTime('2014-02-03'); $date2 = new DateTime('2014-03-02');
$date = new DateTime('2014-03-15');
$obj = new C(); foreach ($obj as $x => $y) { echo $x, $y; }
class Foo Implements ArrayAccess { function offsetExists($k) { return true;} function offsetGet($k) {return 'a';} function offsetSet($k, $v) {} function offsetUnset($k) {} } $x = new Foo(); echo array_key_exists('foo', $x)?'true':'false';
class Bar { private $a = 'b'; public $c = 'd'; } $x = (array) new Bar(); echo array_key_exists('a', $x) ? 'true' : 'false'; echo '-'; echo array_key_exists('c', $x) ? 'true' : 'false';
$data = '$1Ä2'; $count = strlen($data);
$data = '$1Ä2'; echo strlen($data); // 5 echo mb_strlen($data); // 4
$world = 'world'; echo <<<'TEXT' hello $world TEXT;
default_charset = utf-8what will the following code print in the browser?
header('Content-Type: text/html; charset=iso-8859-1'); echo '✂✔✝';
$str = '✔ one of the following'; echo str_replace('✔', 'Check', $str);
$text = 'This is text'; $text1 = <<<'TEXT' $text TEXT; $text2 = <<<TEXT $text1 TEXT; echo "$text2";
function append($str) { $str = $str.'append'; } function prepend(&$str) { $str = 'prepend'.$str; } $string = 'zce'; append(prepend($string)); echo $string;
function increment ($val) { $val = $val + 1; } $val = 1; increment ($val); echo $val;
function increment ($val) { $val = $val + 1; } $val = 1; increment ($val); echo $val; // output = 1
function increment (&$val) { $val = $val + 1; } $val = 1; increment ($val); echo $val; // output = 2
function increment ($val) { ++$val; } $val = 1; increment ($val); echo $val;
function increment ($val) { ++$val; } $val = 1; increment ($val); echo $val; // output = 1
function increment (&$val) { ++$val; } $val = 1; increment ($val); echo $val; // output = 2
function increment ($val) { $_GET['m'] = (int) $_GET['m'] + 1; } $_GET['m'] = 1; echo $_GET['m'];
function counter($start, &$stop) { if ($stop > $start) { return; } counter($start--, ++$stop); } $start = 5; $stop = 2; counter($start, $stop);
1x counter(5, 2) // $start = 5, $stop = 2 2x counter(5, 3) // $start-- = 5, ++$stop = 3 3x counter(5, 4) // $start-- = 5, ++$stop = 4 4x counter(5, 5) // $start-- = 5, ++$stop = 5 5x counter(5, 6) // $start-- = 5, ++$stop = 6Incrementing/Decrementing Operators: http://php.net/manual/en/language.operators.increment.php
function modifyArray (&$array) { foreach ($array as &$value) { $value = $value + 1; } $value = $value + 2; } $array = array (1, 2, 3); modifyArray($array);
class a { public $val; } function renderVal (a $a) { if ($a) { echo $a->val; } } renderVal (null);
function fibonacci (&$x1 = 0, &$x2 = 1) { $result = $x1 + $x2; $x1 = $x2; $x2 = $result; return $result; } for ($i = 0; $i < 10; $i++) { echo fibonacci() . ','; }
function ratio ($x1 = 10, $x2) { if (isset ($x2)) { return $x2 / $x1; } } echo ratio (0);
function increment (&$val) { return $val + 1; } $a = 1; echo increment ($a); echo increment ($a);
$getdata = "foo=bar"; $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $getdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context);
var_dump(boolval(-1));
var_dump(boolval([]));
var_dump(boolval(new StdClass()));
$result = $value1 ??? $value2;Which operator needs to be used instead of ??? so that $result equals $value1 if $value1 evaluates to true, and equals $value2 otherwise? Just state the operator as it would be required in the code.
trait MyTrait { private $abc = 1; public function increment() { $this->abc++; } public function getValue() { return $this->abc; } } class MyClass { use MyTrait; public function incrementBy2() { $this->increment(); $this->abc++; } } $c = new MyClass; $c->incrementBy2(); var_dump($c->getValue());
trait A { public function hello() { return "hello"; } public function world() { return "world"; } } trait B { public function hello() { return "Hello"; } public function person($name) { return ":$name"; } }
class A { protected $x = array(); /* A */ public function getX() { /* B */ return $this->x; /* C */ } } $a = new A(); /* D */ array_push($a->getX(), "one"); array_push($a->getX(), "two"); echo count($a->getX());
class A { public $a = 1; public function __construct($a) { $this->a = $a; } public function mul() { return function($x) { return $this->a*$x; }; } } $a = new A(2); $a->mul = function($x) { return $x*$x; }; $m = $a->mul(); echo $m(3);
$m = $a->mul(); echo $m(3); // output is 6
$m = $a->mul; echo $m(3); // output is 9
class Number { private $v = 0; public function __construct($v) { $this->v = $v; } public function mul() { return function ($x) { return $this->v * $x; }; } } $one = new Number(1); $two = new Number(2); $double = $two->mul()->bindTo($one); echo $double(5);
class Number { private $v; private static $sv = 10; public function __construct($v) { $this->v = $v; } public function mul() { return static function ($x) { return isset($this) ? $this->v*$x : self::$sv*$x; }; } } $one = new Number(1); $two = new Number(2); $double = $two->mul(); $x = Closure::bind($double, null, 'Number'); echo $x(5);
$a = array_merge([1,2,3] + [4=>1,5,6]); echo $a[2];
$array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); /* output Array ( [1] => 2 [hello] => 2 [world] => 1 ) */
$age = $mysqli->real_escape_string($_GET['age']); $name = $mysqli->real_escape_string($_GET['name']); $query = "SELECT * FROM `table` WHERE name LIKE '$name' AND age = $age"; $results = $mysqli->query($query);
// SQL injections $query = "SELECT id, title, body FROM posts WHERE id = " . mysql_real_escape_string($_GET['id']); // This can still be injected: 1 OR 1=1 // Resulting in: SELECT id, title, body FROM posts WHERE id = 1 OR 1=1 // All results are returned. Not convinced this is bad? Ok... 1 OR 1=1 UNION SELECT id, username, password FROM users // Whoops! Why is this injectable? The developer just forgot to quote the numeric ID.Source: http://stackoverflow.com/questions/16173027/mysql-real-escape-string-not-escaping-all-types-of
http_response_code($code);
class test { public $value = 0; function test() { $this->value = 1; } function __construct() { $this->value = 2; } } $object = new test(); echo $object->value;
class T { const A = 42 + 1; } echo T::A;
const MY_CONSTANT; echo MY_CONSTANT; // Output: syntax error, unexpected ';', expecting '='
define('PI', 3.14); class T { const PI = PI; } class Math { const PI = T::PI; } echo Math::PI;
function f(stdClass &$x = NULL) { $x = 42; } $z = new stdClass; f($z); var_dump($z);
try { class MyException extends Exception {}; try { throw new MyException; } catch (Exception $e) { echo "1:"; throw $e; } catch (MyException $e) { echo "2:"; throw $e; } } catch (Exception $e) { echo get_class($e); }
abstract class Graphics { abstract function draw($im, $col); } abstract class Point1 extends Graphics { public $x, $y; function __construct($x, $y) { $this->x = $x; $this->y = $y; } function draw($im, $col) { ImageSetPixel($im, $this->x, $this->y, $col); } } class Point2 extends Point1 { } abstract class Point3 extends Point2 { }
<?xml version="1.0" encoding="utf-8"?> <books> <book id="1">PHP 5.5 in 42 Hours</book> <book id="2">Learning PHP 5.5 The Hard Way</book> </books>Which of the following SimpleXML calls prints the name of the second book?
(Let $xml = simplexml_load_file("books.xml"); .) (Choose 2)
<?xml version='1.0'?> <document> <bar> <foo>Value</foo> </bar> </document>
<?xml version='1.0'?> <foo> <bar> <baz id="1">One</baz> <baz id="2">Two</baz> </bar> </foo>
for ($i = 0; $i < 1.02; $i += 0.17) { $a[$i] = $i; } echo count($a);
$a = array('a', 'b', 'c'); $a = array_keys(array_flip($a));What will be the value of $a?
// isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does. $search_array = array('first' => null, 'second' => 4); // returns false isset($search_array['first']); // returns true array_key_exists('first', $search_array);
$foo = array(true, '0' => false, false => true);
array_combine(array("A","B","C"), array(1,2,3));
$array = array("Sue","Mary","John","Anna");
$array = array(1,2,3); while (list(,$v) = each($array)); var_dump(current($array));
$a = array(0, 1, 2 => array(3, 4)); $a[3] = array(4, 5); echo count($a, 1);
$a = array(28, 15, 77, 43);Which function will remove the value 28 from $a?
$text = <<<EOT The big bang bonged under the bung. EOT; preg_match_all('@b.n?g@', $text, $matches);
echo strtr('Apples and bananas', 'ae', 'ea')
Apples end benenes // 1st: change a -> e, note Apples has not been changed Applas end benenes // 2nd: change e -> a, only where it has not been changed yet, that is, Apples change to Applas
printf('%010.6f', 22);
echo 0x33, ' monkeys sit on ', 011, ' trees.';
preg_match('/^\d+(?:\.[0-9]+)?$/', $test);
preg_match('/^(\d{1,2}([a-z]+))(?:\s*)\S+ (?=201[0-9])/', '21st March 2014', $matches);
$str = "The cat sat on the roof of their house."; $matches = preg_split("/(the)/i", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
md5(rand(), TRUE);
strpos("me myself and I", "m", 2)
$pieces = explode("/", "///");
$test = '/etc/conf.d/wireless'; substr($test, strrpos($test, '/')); // note that strrpos() is being called, and not strpos()
<input type="file" name="myFile" />When this form is submitted, the following PHP code gets executed:
move_uploaded_file( $_FILES['myFile']['tmp_name'], 'uploads/' . $_FILES['myFile']['name'] );Which of the following actions must be taken before this code may go into production? (Choose 2)
<form method="post"> <input type="checkbox" name="accept" /> </form>In the server-side PHP code to deal with the form data, what is the value of $_POST['accept'] ?
<form method="post"> <select name="list"> <option>one</option> <option>two</option> <option>three</option> </select> </form>In the server-side PHP code to deal with the form data, what is the value of $_POST['list'] ?
<input type="image" name="myImage" src="image.png" />The user clicks on the image to submit the form. How can you now access the relative coordinates of the mouse click?
<?php $array = array(true => 'a', 1 => 'b'); print_r($array); ?>
<?php echo str_replace(array("Apple","Orange"), array("Orange","Apple"), "Oranges are orange and Apples are green"); ?>
class C { private static $x = 5; public static function getX() { return self::$x; } } echo C::getX(); // 5
<html> <head> <title> This is a test script. </title> </head> <body> <?php echo 'This is some sample text'; ?> </body> </html>
<?php $a=5; $b=12; $c=10; $d=7; $e=($a*$b)+$c*$d/$a; print($e); ?>What will be the output of the above code?
<?php $b = false; if($b = true) print("true"); else print("false"); ?>
<?php for($x = 1; $x <= 2; $x++){ for($y = 1; $y <= 3; $y++){ if ($x == $y) continue; print("x = $x y = $y"); } } ?>What will be the output? Each correct answer represents a complete solution. Choose all that apply.
<?php var_dump( (bool) 5.8 ); ?>
the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements the special type NULL (including unset variables) SimpleXML objects created from empty tagsEvery other value is considered TRUE (including any resource and NAN).
<?php $a = array (1, 2, 3); $b = array (1 => 2, 2 => 3, 0 => 1); $c = array ('a' => 1, 'b' => 2, 'c' => 3); var_dump ($a == $b); var_dump ($a === $b); var_dump ($a == $c); ?>
<?php function magic($p, $q) { return ($q == 0) ? $p : magic($q, $p % $q); } ?>
<?php echo strtotime("january 1, 1901"); ?>What will be the output of the above PHP script if the older versions of glibc are present in the operating system?
<?php echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1995)); ?>What will be the output of the above script?
<?php $x =25; while($x<10) { $x--; } print ($x); ?>What will be the output when Mark tries to compile and execute the code?
$a = `ls -l`;
<?php echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1965)); ?>What will be the output of the above PHP script?
<html> <head> <title> This is a test script. </title> </head> <body> <?php echo (int) ((0.1 + 0.7) * 10); ?> </body> </html>What will be the output of the PHP script?
<?php define('FOO', 10); $array = array(10 => FOO,"FOO" => 20); print $array[$array[FOO]] * $array["FOO"]; ?>
<?php switch(1) { case 1: print("Book Details"); case 2: print("Book Author"); default: print("Missing Book"); } ?>What will be the output of the script?
<?php $x=0; $i; for($i=0;$i<5;$i++) { $x+=$i; } print($x); ?>What will be the value of x?
<?php function modvalue() { $a=20; $b=4; $c=$a%$b; print($c); } modvalue(); ?>What will be the value of the variable c?
<?php function calc() { $x=10; $b=++$x; print($b); } calc(); ?>What will be the value of the variable b?
$somearray = array("hi", "this is a string", "this is a code");You want to iterate this array and modify the value of each of its elements. Which of the following is the best possible to accomplish the task?
<?php define("GREETING","How are you today?",TRUE); echo constant("greeting"); ?>B.
<?php define("GREETING","How are you today?"); echo constant("greeting"); ?>C.
<?php define("GREETING","How are you today?",FALSE); echo constant("greeting"); ?>D.
<?php define("GREETING","How are you today?",'USECASE'); echo constant("greeting"); ?>
<php echo 0x33, ' birds sit on ', 022, ' trees.'; ?>What will be the output?
<?php $a; for($a=1;$a<=100;$a++) { if($a==50) { continue; } print($a); } ?>What will be the output of the program?
<?php $a = 20; function myfunction($b) { $a = 30; global $a, $c; return $c = ($b + $a); } print myfunction(40) + $c; ?>
<?php echo date('l \t\h\e jS'); ?>
<?php $x = 123 == 0123; ?>
$a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) $a = 0b11111111; // binary number (equivalent to 255 decimal)
<?php $a=12; $b=11; $a>$b ? print($a) : print($b); ?>
<? $a=20%-8; echo $a; ?>
<? echo (int) "1235Jason"; ?>What will be the output?
<?php function odd() { for($i=1; $i<=50; $i=$i+2) { echo "$i"; } } echo "The last value of the variable \$i: $i"; ?>What will be the output?
<? echo (int) "Jason 1235"; ?>What will be the output?
<?php $sale = 200; $sale = $sale- + 1; echo $sale; ?>What will be the output?
<?php function add() { $x=10; $y=5; $x+=$y; } ?>What will be the value of x and y?
<? $a = "b"; $b = 20; echo $$a; ?>What will be the output?
<? $a = "b"; $b = 20; ${20} = $a; echo ${$b}; ?>What will be the output?
<? 10 = $a; echo $a; ?>
<?php $num = -123test; $newnum = abs( $num ); print $newnum; ?>What will be the output?
<?php $a = 6 - 10 % 4; echo $a; ?>What will be the output?
<?php $a=5 < 2; echo (gettype($a)); ?>What will be the output?
$a = 'myVar'; switch($a) { case 0: echo 'case 0'; case 'myVar': echo 'case myVar'; case 'nothing': echo 'case nothing'; }
<?php $s = '<p>Hello</p>'; $ss = htmlentities($s); echo $s; ?>
print strpos('Zend Certified Engineer', 116);
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )Important: If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. In this case, 116 is an Ascii code equivalent to "t", position 8 in the string "Zend Certified Engineer".
<?php for ($i = 5; ; $i++) { if ($i < 10) { break; } } echo $i; ?>Enter the exact script output
$a = 1; $b = 2; $c = 3; echo (++$a) + ($b++) + (++$c) + ($a++) + (++$b) + ($c++);