Moving array element to top in PHP
You can achieve that this way:
$arr = array(
'a1'=>'1',
'a2'=>'2'
);
end($arr);
$last_key = key($arr);
$last_value = array_pop($arr);
$arr = array_merge(array($last_key => $last_value), $arr);
/*
print_r($arr);
will output (this is tested):
Array ( [a2] => 2 [a1] => 1 )
*/
PHP: Move associative array element to beginning of array
You can use the array union operator (+
) to join the original array to a new associative array using the known key (one
).
$myArray = array('one' => $myArray['one']) + $myArray;
// or ['one' => $myArray['one']] + $myArray;
Array keys are unique, so it would be impossible for it to exist in two locations.See further at the doc on Array Operators:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
Move array item with certain key to the first position in an array, PHP
No need to unset keys. To keep it short just do as follow
//appending $new in our array
array_unshift($arr, $new);
//now make it unique.
$final = array_unique($arr);
Demo How to move array elements to top if compared with string?
Use usort()
:
function sortx($a, $b) {
if(strpos($a['p_title'],'Apple ipad')!==false){
return -1;
}
return 1;
}
usort($array, 'sortx');
Whenever the preceding value will contain this string, it will be pushed towards the beginning of the array.If you want to use variable in usort()
function, you need to use objects:
class SortTitles{
public $string;
function sortx($a, $b) {
if(strpos($a['p_title'],$this->string)!==false){
return -1;
}
return 1;
}
public function sort_titles($array){
usort($array, 'self::sortx');
return $array;
}
}
$sort = new SortTitles;
$sort->string = 'Apple ipad';
$array = $sort->sort_titles($array);
Move array element with a particular value to top of array
This should work:
usort($data, function ($a, $b) {
if ($a->Name != "House" && $b->Name == "House") {
return 1;
} elseif ($a->Name == "House" && $b->Name != "House") {
return -1;
} else {
return $b->Total - $a->Total;
}
});
From PHP: usort - Manual:In this case, returnThe comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
1
tells the sorting function that House
is greater than any other value, and -1
that House
is lesser than any other value. Move an array element to a new index in PHP
As commented, 2x array_splice
, there even is no need to renumber:
$array = [
0 => 'a',
1 => 'c',
2 => 'd',
3 => 'b',
4 => 'e',
];
function moveElement(&$array, $a, $b) {
$out = array_splice($array, $a, 1);
array_splice($array, $b, 0, $out);
}
moveElement($array, 3, 1);
redzarf comments: "To clarifyResult:$a
is$fromIndex
and$b
is$toIndex
"
[
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
];
Move array element by associative key to the beginning of an array
This seems, funny, to me. But here ya go:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//store value of key we want to move
$tmp = $test['bla2'];
//now remove this from the original array
unset($test['bla2']);
//then create a new array with the requested index at the beginning
$new = array_merge(array('bla2' => $tmp), $test);
print_r($new);
Output looks like:Array
(
[bla2] => 1234
[bla] => 123
[bla3] => 12345
)
You could turn this into a simple function that takes-in a key and an array, then outputs the newly sorted array.UPDATE
I'm not sure why I didn't default to using uksort
, but you can do this a bit cleaner:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//create a function to handle sorting by keys
function sortStuff($a, $b) {
if ($a === 'bla2') {
return -1;
}
return 1;
}
//sort by keys using user-defined function
uksort($test, 'sortStuff');
print_r($test);
This returns the same output as the code above. how to move to the top an array element
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]]];
Online Demo
Related Topics
Difference Between Directoryiterator and Filesystemiterator
How to Get the Absolute Path to the Public_HTML Folder
Order Properties Should Not Be Accessed Directly - Woocommerce 3.0
How to Use a PHP Class from Another File
Post Ajax Data to PHP and Return Data
Check If the Current Date Is Between Two Dates + MySQL Select Query
What Is the Js Equivalent to the PHP Function Number_Format
Php:Capturing the Command Output
PHP - Good Cronjob/Crontab/Cron Tutorial or Book
Creating and Invoking an Anonymous Function in a Single Statement
Upload Progress Using Pure PHP/Ajax
Calling a PHP Function from an HTML Form in the Same File
Imagemagick Brew Installation with PHP Module in MAC Os X
Make Script Execution to Unlimited
Difference Between $_Server['Document_Root'] and $_Server['Http_Host']