Finding Errors in PHP Array Code
In the following tasks, a programmer wrote some code and possibly made mistakes in it. You must check if the code does what is described. If the code works incorrectly, you must fix the errors.
The code should output the length of the array:
<?php
$arr = [1, 2, 3, 4, 5];
echo strlen($arr);
?>
The code should output the last element of the array:
<?php
$arr = [1, 2, 3, 4, 5];
echo $arr[count($arr)];
?>
The code should find the sum of the array elements:
<?php
$arr = [1, 2, 3, 4, 5];
echo $arr[1] + $arr[2] + $arr[3] + $arr[4] + $arr[5];
?>
The code should output the length of the array:
<?php
$arr = [1, 2, 3, 4, 5];
echo count([$arr]);
?>
The code should find the sum of the array elements:
<?php
$arr = [
'a' => 1,
'b' => 2,
'c' => 3,
];
echo $arr[a] + $arr[b] + $arr[c];
?>
The code should output an array element by the key specified in the variable:
<?php
$arr = [
'a' => 1,
'b' => 2,
'c' => 3,
];
$k = 'a';
echo $arr['$k'];
?>
The code should output the length of the array:
<?php
$arr = [1, 2, 3, 4, 5];
echo count($arr);
?>
The code should output an array element by the key specified in the variable:
<?php
$arr = [
'a' => 1,
'b' => 2,
'c' => 3,
];
$a = 1;
echo $arr[$a];
?>