Task 1: Write a function that takes an array of integers as input and returns the sum of all even numbers in the array.
function sumEvenNumbers(array $numbers): int {
foreach ($numbers as $num) {
if ($num % 2 === 0) {
$sum += $num;
}
}
return $sum;
}
$sum = 0;
A numerical palindrome is a number that reads the same backwards and forwards. An example of numerical palindromes: 101 555 20102.
Task 2: Implement a function to check if a given string is a palindrome (reads the same backward as forward).
function isPalindrome(string $str): bool {
$reversed = strrev($str);
return $str === $reversed;
}
// OR
// Create the function findNumericalPalindrome
// which takes two positive integers as its argument and returns the numerical palindromes
// as an array of $n numerical palindromes that come after $num, including $num.
// Define a function to find numerical palindromes
function findNumericalPalindrome($num, $n)
{
// Initialize an array to store the palindromes
$palindromes = array();
// Loop until the desired number of palindromes is found
while (count($palindromes) < $n) {
// Check if the current number is a palindrome (reads the same forwards and backwards)
if ($num == strrev($num)) {
// If yes, add it to the list of palindromes
$palindromes[] = $num;
}
// Increment the number to check the next one
$num++;
}
// Return the list of palindromes
return $palindromes;
}
// Set the number of palindromes to find
$n = 10;
// Set the starting number
$num = 100;
// Call the function to find palindromes
$palindromes = findNumericalPalindrome($num, $n);
// print_r ($palindromes);
// Loop through each palindrome and print it
foreach ($palindromes as $palindrome) {
// Print each palindrome and move to the next line
echo $palindrome . PHP_EOL .'<br>';
}
Task 3: Create a function to find the second-largest element in an array of integers.
function findSecondLargest(array $numbers): int {
rsort($numbers);
return $numbers[1];
}
Task 1: Design an API endpoint to retrieve a user's profile information by their ID.
Solution:
The API endpoint
GET /api/users/{user_id}Response1 (JSON):
{
"user_id": 1,
"name": "Gilbert Ozioma",
"email": "gilbertozioma0@gmail.com",
"bio": "Backend Web Developer",
"url": "https://about.me/gilbertozioma",
"created_at": "2023-08-07T12:34:56Z"
}Pseudo-code implementation of the API endpoint:
<?php
// Function to retrieve user profile by ID
function get_user_profile($user_id) {
// Fetch user profile from the database or any other data source
$user_profile = getUserProfileFromDatabase($user_id);
return $user_profile;
}
// Check if the request method is GET and the user_id parameter exists
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['user_id'])) {
$user_id = $_GET['user_id'];
$user_profile = get_user_profile($user_id);
// Set the appropriate content type and status code
header('Content-Type: application/json');
if ($user_profile) {
http_response_code(200);
echo json_encode($user_profile);
} else {
http_response_code(404);
echo json_encode(array("error" => "User not found"));
}
} else {
// Return an error for unsupported requests
http_response_code(405);
echo json_encode(array("error" => "Method Not Allowed"));
}
?>
Task 2: Implement an API endpoint to create a new post with title and content.
Solution:
The API endpoint:
POST /api/posts
Request (JSON):
{
"title": "New Post Title",
"content": "This is the content of the new post."
}Response2 (JSON):
{
"status": "success",
"message": "Post created successfully",
"post_id": 12345
}
<?php
// Function to create a new post
function create_new_post($data) {
// Generate a unique post ID
$post_id = generateUniqueId();
// Save the post to the database with the provided title and content
savePostToDatabase($post_id, $data['title'], $data['content']);
return $post_id;
}
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the JSON data from the request body
$data = json_decode(file_get_contents('php://input'), true);
// Ensure that the required fields are provided (title and content)
if (isset($data['title']) && isset($data['content'])) {
// Create the new post
$post_id = create_new_post($data);
// Set the appropriate content type and status code
header('Content-Type: application/json');
http_response_code(201);
// Respond with the success message and the new post's ID
echo json_encode(array(
"status" => "success",
"message" => "Post created successfully",
"post_id" => $post_id
));
} else {
// Return an error if title and content are not provided
http_response_code(400);
echo json_encode(array("error" => "Title and content are required"));
}
} else {
// Return an error for unsupported requests
http_response_code(405);
echo json_encode(array("error" => "Method Not Allowed"));
}
Task 1: Write a SQL query to retrieve all users from the "users" table with their names and email addresses.
Solution:
SELECT name, email FROM users;
Task 2: Write a SQL query to calculate the average age of all users in the "users" table.
Solution:
SELECT AVG(age) AS average_age FROM users;
Task 3: Write a SQL query to find the top 5 products with the highest sales in the "sales" table.
Solution:
SELECT product_name, SUM(quantity) AS total_sales
FROM sales
GROUP BY product_name
ORDER BY total_sales DESC
LIMIT 5;
Task 1: Design an API endpoint to retrieve a list of all products with their details from the "products" table.
Solution:
// Route definition using Laravel's routing
Route::get('/api/products', 'ProductController@index');
// Controller method to handle the request
public function index() {
$products = Product::all();
return response()->json($products);
}
Task 2: Implement an API endpoint to create a new order for a customer with multiple products.
Solution:
// Route definition using Laravel's routing
Route::post('/api/orders', 'OrderController@store');
// Controller method to handle the request
public function store(Request $request) {
$validatedData = $request->validate([
'customer_id' => 'required|integer',
'products' => 'required|array',
]);
// Create the order and store it in the database
$order = Order::create([
'customer_id' => $validatedData['customer_id'],
]);
// Attach products to the order
$order->products()->attach($validatedData['products']);
return response()->json(['message' => 'Order created successfully'], 201);
}
Task 3: Design an API endpoint to delete a specific user from the "users" table.
Solution:
// Route definition using Laravel's routing
Route::delete('/api/users/{id}', 'UserController@destroy');
// Controller method to handle the request
public function destroy($id) {
$user = User::find($id);
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
// Delete the user from the database
$user->delete();
return response()->json(['message' => 'User deleted successfully'], 200);
}
Leave a Comment