Reputation:
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 !
Upvotes: 0
Views: 61
Reputation: 125
$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);
Upvotes: 0
Reputation: 897
if ($actual[0] != 'apple') {
unset($actual[array_search('apple', $actual)]);
array_unshift($actual, "apple");
}
print_r($actual);
Upvotes: 1
Reputation: 522135
$actual = array("orange", "banana", "apple", "raspberry", "mango","pineapple");
$apple = $actual[2];
unset($actual[2]);
array_unshift($actual, $apple);
Upvotes: 2