How to change php array position with condition in Php

Viewed 55

I am working with PHP,I have array and i want to change position of array, i want to display matching value in first position,For example i have following array

$cars=('Toyota','Volvo','BMW');

And i have variable $car="BMW" And i want to match this variable with array and if match then this array value should be at first in array so expected result is (matching record at first position)

$cars=('BMW','Volvo','Toyota');

How can i do this ?

3 Answers

You can use array_search and array_replace for this purpose. try below mentioned code

$cars=array(0 =>'Toyota',1 =>'Volvo',2 =>'BMW');
$car="BMW";

$resultIndex = array_search($car, $cars); //get index 

if($resultIndex)
{
$replacement = array(0 =>$car,array_search($car, $cars)=>$cars[0]); //swap with  0 index 
$cars = array_replace($cars, $replacement); //replace 
}

print_r($cars);

This can be solved in one line with array_merge and array_unique array functions.

$cars=['Toyota','Volvo','BMW'];
$car="BMW";

$cars2 = array_unique(array_merge([$car],$cars));
//$cars2: array(3) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" [2]=> string(5) "Volvo" }

$car is always at the beginning of the new array due to array_merge. If $car already exists in the $cars array, array_unique will remove it. If $car is not present in the $cars array, it is added at the beginning. If this behavior is not desired, you can use in_array to test whether $car is also contained in the $cars array.

The simplest is to "sort" by "Value = BMW", "Value != BMW".

The function that sorts and resets the keys (i.e. starts the resulting array from 0, which you want) is usort (https://www.php.net/manual/en/function.usort.php)

So your comparison function will be If ($a == "BMW") return 1, elseif ($b == "BMW") return -1, else return 0; (Paraphrased, don't expect that to work exactly - need to leave a bit for you to do!)

Related