I have an array and I want to show a specific order when I click on the key. When I click on '5', the result would be '5,6,4'. When I click on '6', I would get '6,4,5'.
Array
(
[0] => 4
[1] => 5
[2] => 6
)
Thanks in advance.
Get all the values until the clicked value to another array say - $frontArray
and merge it to the main array.
//get the clicked value
$clickedValue = your clicked value;
//find the key
$key = array_search($clickedValue, $myArray);
$frontArray = array();
if ($key !== FALSE) {
$keyReached = FALSE;
foreach ($myArray as $k => $v) {
if ($key == $k) {
$keyReached = TRUE;
}
if (!$keyReached) {
$frontArray[] = $v;
unset($myArray[$k]);
}
}
$myArray = array_merge($myArray, $frontArray);
//re-index the array
$myArray = array_values($myArray);
}
print_r($myArray); // this gets modified as per the clicked value
I've tested this using your example and it works fine.
Use array_splice to split array to two - before and after
$ar = [4,5,6];
$v = 5;
if (false !== ($i = array_search($v, $ar)) {
$b = array_splice($ar, $i+1);
$ar = array_merge($b, $ar);
}
print($ar);