0% found this document useful (0 votes)
52 views

PHP and Mysql Exam

The document describes a PHP coding exam with 3 questions. For question 1, the applicant wrote a PHP program to find the best deal out of two chip promotions by calculating the price per item. The program determined promotion #2 (buy 100 chips for $30) was the better deal. For question 2, the applicant wrote a PHP program to check if a given year is a leap year. The program returns "Leap year" or "Not a leap year" based on whether the number of days in February for the given year is 29 or not. For question 3, the applicant wrote a PHP program to loop through JSON data containing student names, ages, and schools and display it in a formatted

Uploaded by

aven vlogs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

PHP and Mysql Exam

The document describes a PHP coding exam with 3 questions. For question 1, the applicant wrote a PHP program to find the best deal out of two chip promotions by calculating the price per item. The program determined promotion #2 (buy 100 chips for $30) was the better deal. For question 2, the applicant wrote a PHP program to check if a given year is a leap year. The program returns "Leap year" or "Not a leap year" based on whether the number of days in February for the given year is 29 or not. For question 3, the applicant wrote a PHP program to loop through JSON data containing student names, ages, and schools and display it in a formatted

Uploaded by

aven vlogs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Applicant: Jan Michael Quisto

PHP CODING EXAM


1. A store provided two deals for a bag of chips. Write a program in
PHP to find the best
deal to purchase the item. And given the program you wrote,
which of the 2 deals is the
better option?
PROMO # QUANTITY PRICE
1 70 35
2 100 30

Program:
PHP v7.4.30

Directories:
Classes
|_ Process.php
|_ View.php
view
|_ template
|_ promo.phtml
index.php

Source:

Classes/Process.php

<?php
namespace Classes;
class Process
{
/**
* @var array[]
*/
protected $data;
/**
* @var array[]
*/
protected $bestDeal;

public function __construct() {


$this->loadData();
}

/**
* @return $this
*/
public function execute() {
$this->findBestDeal();
return $this;
}

/**
* @return $this
*/
protected function loadData() {
$this->data = [
[
"promo" => "1",
"quantity" => 70,
"price" => 35
],
[
"promo" => "2",
"quantity" => 100,
"price" => 30
]
];
return $this;
}

/**
* @return $this
*/
protected function findBestDeal() {
foreach ($this->data as $item) {
if (empty($this->bestDeal) || $this-
>compareToCurrentBestDeal($item)) {
$this->bestDeal = [
"promo" => $item["promo"],
"price_per_item" => $item["price"]/$item["quantity"]
];
}
}
return $this;
}

/**
* @param $promo
* @return bool
*/
protected function compareToCurrentBestDeal($promo) {
return $this->bestDeal["price_per_item"] >
$promo["price"]/$promo["quantity"];
}

/**
* @return array[]
*/
public function getBestDeal() {
return $this->bestDeal;
}

/**
* @return array[]
*/
public function getData() {
return $this->data;
}
}

Classes/View.php

<?php
namespace Classes;

class View {

/**
* @var Process
*/
private $process;

public function __construct(Process $process) {


$this->process = $process;
$this->render();
include('view/template/promo.phtml');

/**
* @return $this
*/
public function render() {
$this->process->execute();
return $this;
}
/**
* @return array[]
*/
public function getBestDeal() {
return $this->process->getBestDeal();
}

/**
* @return array[]
*/
public function getData() {
return $this->process->getData();
}
}

view/template/promo.phtml

<?php
$items = $this->getData();
$bestDeal = $this->getBestDeal();
foreach ($items as $key => $item): ?>
<div class="promo-deals">
<span>Buy <?=$item["quantity"]?> for</span>
<strong>$<?=$item["price"]?></strong>
<?php if($bestDeal["promo"] == $item["promo"]): ?>
<sup><i>BEST DEAL</i></sup>
<?php endif ?>

</div>
<br/>
<?php endforeach;

index.php

<?php
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\Process;
use Classes\View;
$process = new Process();
$block = new View($process);
Better Option:

Promo #2: Buy 100 for $30.

2. Leap years are years where an extra day is added to the end of
the shortest month,
February. How do you check if a year is a leap year or not?
INPUT: 2022
OUTPUT: Not a leap year
INPUT: 2020
OUTPUT: Leap year

Program:
PHP v7.4.30

Directories:
Classes
|_ Calendar.php
|_ ViewLeapYear.php
view
|_ template
|_ leap_year.phtml
index.php
process.php

Source:

Classes/Calendar.php

<?php
namespace Classes;
class Calendar
{
public function __construct() {}

/**
* @return $this
*/
public function execute() {
if(isset($_POST["year"])) {
if($this->checkIfLeapYear($_POST["year"])) {
$_SESSION['message'] = "{$_POST["year"]} is leap year";
} else {
$_SESSION['message'] = "{$_POST["year"]} is not leap year";
}
}
header('Location: index.php');
return $this;
}

/**
* @param $year
* @return bool
*/
protected function checkIfLeapYear($year) {
return cal_days_in_month(CAL_GREGORIAN,2,$year) == 29;
}

Classes/ViewLeapYear.php

<?php
namespace Classes;

class ViewLeapYear {

/**
* @var string
*/
protected $message;

public function __construct() {


$this->render();
}

/**
* @return $this
*/
public function render() {
$this->loadSessionMessage();
include('view/template/leap_year.phtml');
return $this;
}

/**
* @return void
*/
protected function loadSessionMessage() {
if(isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
}
}

/**
* @return string
*/
public function getMessage() {
return $this->message;
}

view/template/leap_year.phtml

<div class="form-wrap">
<form action="process.php" method="post" />
<div class="input-wrap">
<input type="number" name="year" class="year-input text-box" />
</div>
<br />
<div class="panel-wrap">
<button type="submit">Check If Leap Year</button>
</div>
</form>
<?php if($this->getMessage()): ?>
<br/>
<p><strong><?=$this->getMessage()?></strong></p>
<?php endif ?>
</div>

index.php

<?php
session_start();
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\ViewLeapYear;
$block = new ViewLeapYear();
session_unset();

process.php

<?php
session_start();
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\Calendar;
$calendar = new Calendar();
$calendar->execute();

3. Write a php program to loop over the json data. Suppose, you
have the following json
data.
[
{
"name" : "John Garg",
"age" : "15",
"school" : "Ahlcon Public school"
},
{
"name" : "Smith Soy",
"age" : "16",
"school" : "St. Marie school"
},
{
"name" : "Charle Rena",
"age" : "16",
"school" : "St. Columba school"
}
]

And display it as below:


John Garg -> 15 -> Ahlcon Public school
Smith Soy -> 16 -> St. Marie school
Charle Rena -> 16 -> St. Columba school

Program:
PHP v7.4.30

Directories:
Classes
|_ JsonClass.php
|_ JsonView.php
view
|_ template
|_ json_view.phtml
index.php

Source:

Classes/JsonClass.php

<?php
namespace Classes;
class JsonClass
{

/**
* @var string
*/
protected $data;

/**
* @var array[]
*/
protected $jsonLoaded;

public function __construct() {


$this->loadData();
}

/**
* @return $this
*/
public function execute() {
$this->loadJsonData();
return $this;
}

/**
* @return $this
*/
protected function loadData() {
$this->data = '[
{
"name" : "John Garg",
"age" : "15",
"school" : "Ahlcon Public school"
},
{
"name" : "Smith Soy",
"age" : "16",
"school" : "St. Marie school"
},
{
"name" : "Charle Rena",
"age" : "16",
"school" : "St. Columba school"
}
]
';
return $this;
}

/**
* @return $this
*/
protected function loadJsonData() {
$this->jsonLoaded = json_decode($this->data);
return $this;
}

/**
* @return array[]
*/
public function getLoadedJson() {
return $this->jsonLoaded;
}

}
Classes/JsonView.php

<?php
namespace Classes;

class JsonView {

/**
* @var JsonClass
*/
private $process;

public function __construct(JsonClass $process) {


$this->process = $process;
$this->render();
include('view/template/json_view.phtml');

/**
* @return $this
*/
public function render() {
$this->process->execute();
return $this;
}

/**
* @return array[]
*/
public function getValues() {
return $this->process->getLoadedJson();
}
}

view/template/json_view.phtml

<?php $items = $this->getValues(); ?>


<?php foreach ($items as $key => $item): ?>
<div class="names-wrapper">
<p class="details">
<span class="name-wrap"><?=$item->name?></span> &rarr;
<span class="age-wrap"><?=$item->age?></span> &rarr;
<span class="school-wrap"><?=$item->school?></span>
</p>
</div>
<?php endforeach;

index.php

<?php
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\JsonClass;
use Classes\JsonView;
$process = new JsonClass();
$block = new JsonView($process);

4. Write a function that takes a string and calculates the number of


letters and digits within
it. Return the result as an array.
NOTES:
● Tests contain only alphanumeric characters.
● Spaces are not letters.
● All tests contain valid strings.
INPUT : Hello World
OUTPUT : array("LETTERS" => 10, "DIGITS" => 0)

Function Source ( countLettersDigits($input) ):

/**
* @param $value string
* @return array
*/
public function countLettersDigits($value) {
$lettersOnly = preg_replace ('/[^A-Za-z]/u', '', $value);
$digitsOnly = preg_replace ('/[^\d+]/u', '', $value);
return [
"LETTERS" => strlen($lettersOnly),
"DIGITS" => strlen($digitsOnly)
];
}
RUN EXAMPLE:

var_dump(Class::countLettersDigits (“Hello World”));

5. Create a function that transforms sentences ending with multiple


question marks ? or
exclamation marks ! into a sentence only ending with one without
changing punctuation
in the middle of the sentences.
INPUT: Ana! What went wrong?????????
OUTPUT: Ana! What went wrong?

Function Source:

/**
* @var string
*/
protected $endString = "";

/**
* @var string
*/
protected $newString = "";

/**
* @param $value
* @return string
*/
protected function checkLastCharacter($value) {
$endString = substr(rtrim($value), -1);
switch($endString) {
case "!":
$this->newString = rtrim($value,"!");
$this->endString = "!".$this->endString;
$this->checkLastCharacter($this->newString);
break;
case "?":
$this->newString = rtrim($value,"?");
$this->endString = "?".$this->endString;
$this->checkLastCharacter($this->newString);
break;
default:
$this->newString = $value;
}
return $this->newString.$this->endString;
}

/**
* @param $value
* @return string
*/
public function trimQuestionExclamationMark($value) {
return $this->checkLastCharacter($value);
}

RUN:

$sentence = "Ana! What went wrong?????????";


Class::trimQuestionExclamationMark($sentence);

6. Given a list of numbers, create a function that removes 25% from


every number in the
list except the smallest number, and adds the total amount
removed to the smallest
number.
INPUT: [4, 1, 4]
OUTPUT: [3, 3, 3]
INPUT: [16, 10, 8]
OUTPUT: [12, 7.5, 14.5]

Function Source:

/**
* @param array $values
* @param $percent
* @return array|float[]|int[]
*/
public function calculateArray(array $values, $percent = 25) {
$percentage = $percent/100;
$minValue = min($values);
$totalRemoved = 0;
$excluded = [];
foreach ($values as $key => $value) {
if($value != $minValue) {
$toRemove = $value*$percentage;
$totalRemoved = $totalRemoved+$toRemove;
$values[$key] = $value-$toRemove;
} else {
$excluded[] = $key;
}
}
return array_map(function ($v, $k) use ($minValue, $totalRemoved,
$excluded) {
return $v == $minValue && in_array($k,$excluded) ? $minValue+
$totalRemoved : $v;
}, $values, array_keys($values));
}

RUN EXAMPLE:

$values = [5,6,3,4,8,7];
var_dump(Class::calculateArray($values, 25));

7. Create a function that splits a string into an array of identical clusters.


INPUT: 5556667788
OUTPUT: ["555", "666", "77", "88"]

Function Source:

/**
* @param $value string
* @return array
*/
public function arrayGroupClusters(string $value) {
$array = str_split(preg_replace ('/\s/u', '', $value));
$newSet = [];

foreach($array as $key=>$item) {
$checkValue = preg_grep('~'.$item.'~', $newSet);
if(!empty($checkValue)) {
foreach($checkValue as $k=>$value) {
$newSet[$k] = $value.$item;
}
} else {
$newSet[] = $item;
}
}
return $newSet;
}

RUN EXAMPLE:

var_dump(Class:: arrayGroupClusters (5556667788));

MYSQL EXAM
MYSQL EXAM
1. Write a mysql statement to determine the age of each of the
students.
+----+--------------+------------+------------+
| id | name | department | birth |
+----+--------------+------------+------------+
| 1 | Maria Gloria | CS | 1994-03-12 |
| 2 | John Smith | IT | 1993-02-07 |
| 3 | Gal Rao | CS | 1992-09-11 |
| 4 | Jakey Smith | EC | 1990-08-31 |
| 5 | Rama Saho | IT | 1994-12-09 |
| 6 | Maria Gaga | EC | 1993-10-09 |
+----+--------------+------------+------------+

GIVEN:
Table Name = students

STATEMENT:

SELECT
`students`.`name`,
TIMESTAMPDIFF(year, `students`.`birth`, NOW()) as `age`
FROM `students`;

2. Write a mysql statement to get the names of students containing exactly four
characters.
+----+-------+---------+------------+
| id | name | dept_id | birth |
+----+-------+---------+------------+
| 1 | Maria | 2 | 1994-03-12 |
| 2 | John | 1 | 1993-02-07 |
| 3 | Gal | 4 | 1992-09-11 |
| 4 | Jakey | 2 | 1990-08-31 |
| 5 | Rama | 1 | 1994-12-09 |
| 6 | Maria | 4 | 1993-10-09 |
+----+-------+---------+------------+

GIVEN:
Table Name = students

STATEMENT:

SELECT
`students`.`name`
FROM `students `
WHERE CHAR_LENGTH(`students`.`name`) = 4;

3. What happens when the column is set to AUTO INCREMENT and if


you reach maximum
value in the table?

Answer:
If the column is set to AUTO INCREMENT and reach its maximum
value, the process to generate the sequence number will fail and no
further data will be added (no rows can be inserted in the table).

4. How can you see all indexes defined for a table?

Answer:

Run the MySQL statement

SHOW INDEX FROM `db_name`.`table_name`;

5. Is Mysql query case sensitive?

Answer:

MySQL query is not case sensitive. You can write it in lower cases,
upper cases, camel cases, or mix of mentioned cases.

6. How to display the top 50 rows?

Statement:

SELECT * FROM `table_name`


LIMIT 0, 50;

You might also like