Change the index of an array to Topmost position in php

主宰稳场 提交于 2021-01-29 07:03:18

问题


I have an array say

$actual = array("orange", "banana", "apple", "raspberry", "mango","pineapple");

Now I want the "apple" value to hold the first index in the array such that it holds the first position and remaining values follow it as show below.

Desired array :

$output = array ("apple", "orange", "banana", "raspberry", "mango", "pineapple");

How can I achieve this ?

Thanks for reading !


回答1:


$actual = array("orange", "banana", "apple", "raspberry", "mango","pineapple");
$apple = $actual[2];
unset($actual[2]);
array_unshift($actual, $apple);



回答2:


if ($actual[0] != 'apple') {
        unset($actual[array_search('apple', $actual)]);
        array_unshift($actual, "apple");
}

print_r($actual);



回答3:


$actual = array("orange", "banana", "apple", "raspberry", "mango","pineapple");
        for($i=0; $i<sizeof($actual); $i++)
        {
            if($actual[$i] == "apple")
            {
                for($j=$i; $j>=0; $j--)
                {
                    if($j != 0)
                    {
                        $el=$actual[$j];
                        $actual[$j]=$actual[$j-1];
                        $actual[$j-1]=$el;  
                    }
                }
            }
        }
        print_r($actual);


来源:https://stackoverflow.com/questions/22909426/change-the-index-of-an-array-to-topmost-position-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!