1

I have a php array as follows,

<?php
    $arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');

?>

How to set xyz value as first element with minimum loop,if the value exist.

Expected Result

<?php
    $arr = array('ab'=>'xyz', 'op'=>'pqr','mn'=>'abcd');
?>
1
  • @notme, alfasin is correct, but I might suggest that if you require order in this array, that you consider storing your data in a different manner. You can have an array of arrays, for example. Commented Jul 5, 2012 at 6:04

2 Answers 2

4
$ab = $array['ab'];
unset($array['ab']);
$array = array('ab' => $ab) + $array;

If the key itself is unknown, find it first:

$key = array_search('xyz', $array);
$tmp = $array[$key];
unset($array[$key]);
$array = array($key => $tmp) + $array;

Or go with a sort:

uasort($array, function ($a, $b) {
    if ($a == 'xyz') return -1;
    if ($b == 'xyz') return 1;
    return 0;
});
Sign up to request clarification or add additional context in comments.

Comments

-2
<?php
    $arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');
    ksort($arr);
    echo '<pre>';
    print_r($arr);

1 Comment

This won't give the result that OP is trying to get, it'll sort the array by key.

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.