'how to move to the top an array element [duplicate]
I have selected rows from a table
target row is a row having id equal to $_GET['id']
I want to move it at the top of rows
$sq = "select * from video order by ind asc";
$st = $db->prepare($sq);
$st->execute();
$rows = $st->fetchAll();
if(isset($_GET['id'])){
foreach($rows as $row){
if($row['id'] == $_GET['id']){
unset($rows[$row]); // error line
$rows = $row + $rows;
}
}
}
error - Illegal offset type in unset...
also - is there a shorter way to do this, i.e. to avoid loop
something like:
$rows[having id equal to $_GET['id']] -> move-to-top
Solution 1:[1]
For this line,
unset($rows[$row]); // error line
you need to unset the key in $rows and not $row itself which is a value in the foreach loop.
So, for unsetting it would look like:
<?php
foreach($rows as $key => $row){
if($row['id'] == $_GET['id']){
unset($rows[$key]);
// code line to move to the top
break;
}
}
Don't use $rows = $row + $rows; kind of syntax as it makes it difficult to read during code reviews.
For a shorter syntax, you can use array_filter to filter out the row and then perform a swap taking the help of symmetric-array-destructuring.
Snippet:
<?php
$row = array_filter($rows, fn($arr) => $arr['id'] == $testID);
[$rows[array_keys($row)[0]], $rows[0]] = [$rows[0], $rows[array_keys($row)[0]]];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nice_dev |
