1

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?

1
  • 1
    lol is there a reason to do that? Commented Mar 28, 2011 at 18:24

5 Answers 5

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I found unshift to be the best bet also. Thanks Rocket!
1
$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);
}

Comments

1

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

$people[0] = "Charlie";

2 Comments

I think the OP wants to remove 'Charlie', make it the first element, and push everything else down.
You think so ... maybe you're thinking too much!
0
$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.

Comments

0
$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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.