skip to Main Content

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


  1. Do not assign

    sort($oddNumbers);
    

    to

    $oddNumbers
    

    because sort always return true, it accepts pass by reference.

    Example:

    // Create an array of odd numbers
    $oddNumbers = [7, 1, 5, 9, 3];
    
    // Sort the array in ascending order using the sort() function
    sort($oddNumbers);
    
    // Print the sorted array
    print_r($oddNumbers);
    

    will result in

    Array
    (
        [0] => 1
        [1] => 3
        [2] => 5
        [3] => 7
        [4] => 9
    )
    
    Login or Signup to reply.
  2. Like that?

    <?php
    $array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; // ...,2,9,0
    $odds = [];
    $even = [];
    
    foreach ($array as $val) 
    {
        if($val % 2 !== 0) 
        {
            $odds[] = $val;
        } 
        else 
        {
            $even[] = $val;
        }
    }
    
    sort($odds);
    rsort($even);
    
    $array = [];
    foreach ($odds as $key => $val) 
    {
        $array[] = $val;
        if(isset($even[$key])) 
        {
            $array[] = $even[$key];
        }
    }
    
    print_r($array);
    // output:
    Array
    (
        [0] => 1
        [1] => 8
        [2] => 3
        [3] => 6
        [4] => 5
        [5] => 4
        [6] => 7
        [7] => 2
        [8] => 9
        [9] => 0
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search