开发者

php search array for string, then if found, move that string to first item of array

开发者 https://www.devze.com 2023-02-20 13:43 出处:网络
so let\'s say i have an array: $people[0] = \"Bob\"; $people[1] = \"Sally\"; $people[2] = \"开发者_运维技巧Charlie\";

so let's say i have an array:

$people[0] = "Bob";
$people[1] = "Sally";
$people[2] = "开发者_运维技巧Charlie";
$people[3] = "Clare";

if (in_array("Charlie", $people)) {
    //move Charlie to first item in array
}

What would be the most efficient way to get Charlie to the first item in the array?


You can use array_unshift() to prepend elements to an array.

$pos = array_search("Charlie", $people);
if($pos !== FALSE){
  $item = $people[$pos];
  unset($people[$pos]);
  array_unshift($people, $item);
}


$people[0] = "Bob"; $people[1] = "Sally"; $people[2] = "Charlie"; $people[3] = "Clare";

$personToSearch = "Charlie";

$personIndex = array_search($personToSearch, $people);

if ($personIndex !== false)
{
  unset($people[$personIndex]);
  $people = array_merge(array($personToSearch), $people);
}


What would be the most efficient way to get Charlie to the first item in the array?

$people[0] = "Charlie";


$results = array_search('Charlie', $people);
if ($results !== FALSE) { then
    $people[$results] = $people[0]; // swap the original 'first' person to where Charlie was.
    $people[0] = 'Charlie';
}

Now, that assumes you don't care about preserving the rest of the array's original order. If you want to move Charlie to the front and shift everything in between up a slot, that's another matter entirely.


$position = array_search('Charlie', $people);

if ($position !== FALSE)
{
  // Remove it
  $charlie  = array_splice($people, $position, $1);
  // Stick it on the beginning
  array_unshift($people, $charlie);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号