Home > other >  How to change php array position with condition in Php
How to change php array position with condition in Php

Time:09-08

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 ?

CodePudding user response:

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);

CodePudding user response:

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