Complete the code to return the sum of two numbers.
<?php
function add($a, $b) {
return [1];
}
echo add(3, 4);The function should return the sum of $a and $b, so return $a + $b; is correct.
Complete the code to return the length of a string.
<?php
function getLength($str) {
return [1];
}
echo getLength("hello");count() which is for arrays.size() or length().In PHP, strlen() returns the length of a string.
Fix the error in the function to return the first element of an array.
<?php
function firstElement($arr) {
return [1];
}
echo firstElement([10, 20, 30]);To access the first element of an array in PHP, use square brackets with index 0: $arr[0].
Fill both blanks to return a new array with squares of numbers greater than 3.
<?php
function squaresAboveThree($numbers) {
return array_combine(
array_filter($numbers, fn($n) => $n [1] 3),
array_map(fn($n) => $n[2]2, array_filter($numbers, fn($n) => $n > 3))
);
}
print_r(squaresAboveThree([1, 2, 3, 4, 5]));The function filters numbers greater than 3 using > and squares them using the exponent operator **.
Fill all three blanks to return an associative array with uppercase keys and values greater than 10.
<?php
function filterAndUppercase($data) {
$result = [];
foreach($data as [3] => [2]) {
if([2] > 10) {
$result[[1]] = [2];
}
}
return $result;
}
print_r(filterAndUppercase(['a' => 5, 'b' => 15, 'c' => 20]));The function returns an array with keys converted to uppercase using strtoupper($key), values as $value, and iterates over $key in the input array.