trying to solve a kata here where the instructions are:
You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.
Examples
[7, 1] => [1, 7]
[5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]
I come up with this code
function sortArray(array $arr) : array {
$oddNumbers = [0];
$oddNumbersPlaced = 0;
for ($i = 0; $i < count($arr); $i++)
if ($arr[$i] % 2 != 0) {
$oddNumbers[$oddNumbersPlaced] = $arr[$i];
$arr[$i] = 'a';
$oddNumbersPlaced =+ 1;
};
$oddNumbers = sort($oddNumbers);
for ($n = 0; $n < count($arr); $n++){
$oddPlaced = 0;
if ($arr[$n] == 'a'){
$arr[$n] = $oddNumbers[$oddPlaced];
$oddPlaced = $oddPlaced+1;
}
}
return $arr;
}
but get an error at line 17 :
$arr[$n] = $oddNumbers[$oddPlaced];
which says ‘Trying to access array offset on value of type bool’;
can someone explain to me how and where do i get a bool value plz ?
2
Answers
Do not assign
to
because sort always return true, it accepts pass by reference.
Example:
will result in
Like that?