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
For this line,
you need to unset the key in
$rowsand not$rowitself which is a value in the foreach loop.So, for unsetting it would look like:
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_filterto filter out the row and then perform a swap taking the help ofsymmetric-array-destructuring.Snippet:
Online Demo