John Davidson

php - Undefined offset when using bubble sort on associative array

0 comments
Message:


I have this function to bubblesort an associative array based on a key input with the option to order by descending or ascending:


function bubbleSort($input, $key, $order){
while (true){
$end = false;
$swapped = false;
$idx = 0;
do {
$x = $input[$idx];
$y = $input[$idx + 1];
$x_param = $x[$key];
$y_param = $y[$key];
if (is_null($y)) {
$end = true;
continue;
}
if ($order == "desc"){
if ($x_param < $y_param){
$input[$idx] = $y;
$input[$idx + 1] = $x;
$swapped = true;
}
}
else{
if ($y_param < $x_param){
$input[$idx] = $y;
$input[$idx + 1] = $x;
$swapped = true;
}
}
$idx++;
}
while ($end == false);
if ($swapped == false) {break;}
}
return $input;
}

In this example I'll use it on this associative array:


$array = array(
array("Student Number" => 001, "Student name" => "David", "Student age" => 21),
array("Student Number" => 002, "Student name" => "Jonas", "Student age" => 15),
array("Student Number" => 003, "Student name" => "Katy", "Student age" => 23));

If I print it with print_r like this it will successfully sort and print it:


print_r(bubbleSort($array, "Student age", "desc"));

The problem is I get Notice: Undefined offset: 3 for the line containing $y = $input[$idx + 1];


As well as Notice: Trying to access array offset on value of type null for the line containing $y_param = $y[$key];


It does print a properly sorted asc array, so the code works.


But is there a way to phrase my code to not get the notice ?


Screenshot of the full output I get (with a lot of notices).



My Answer:
To avoid the "Undefined offset" notice, you can modify your code to check if the next index exists before accessing it. Here's an updated version of your bubbleSort function:

php
function bubbleSort($input, $key, $order){
$length = count($input);
while (true){
$end = false;
$swapped = false;
$idx = 0;
do {
$x = $input[$idx];
$y = isset($input[$idx + 1]) ? $input[$idx + 1] : null;
if (is_null($y)) {
$end = true;
continue;
}
$x_param = $x[$key];
$y_param = $y[$key];
if ($order == "desc"){
if ($x_param < $y_param){
$input[$idx] = $y;
$input[$idx + 1] = $x;
$swapped = true;
}
}
else{
if ($y_param < $x_param){
$input[$idx] = $y;
$input[$idx + 1] = $x;
$swapped = true;
}
}
$idx++;
}
while ($end == false);
if ($swapped == false) {break;}
}
return $input;
}


By using `isset($input[$idx + 1]) ? $input[$idx + 1] : null`, you are checking if the next index exists before trying to access it. This should prevent the "Undefined offset" notice from appearing.

Rate this post

3 of 5 based on 9783 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us