Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift an element to the end of array

I have an array which contains list of pagrank values. Consider below array:

Array
(
    [0] => stdClass Object
        (
            [pagerank] => 3
        )

    [1] => stdClass Object
        (
            [pagerank] => 1
        )

    [2] => stdClass Object
        (
            [pagerank] => R
        )

    [3] => stdClass Object
        (
            [pagerank] => 2
        )

    [4] => stdClass Object
        (
            [pagerank] => 7
        )

)

I want to shift/move page rank with 'R' like:

[2] => stdClass Object
        (
            [pagerank] => R
        )

to the end of array and it should be on last index of array?

Edit: The array key is unknown.

like image 761
Irfan Avatar asked Jul 19 '13 13:07

Irfan


3 Answers

$item = $array[2];
unset($array[2]);
array_push($array, $item); 
like image 50
Mike Thomsen Avatar answered Oct 01 '22 02:10

Mike Thomsen


If the index is unknown:

foreach($array as $key => $val) {
    if($val->pagerank == 'R') {
        $item = $array[$key];
        unset($array[$key]);
        array_push($array, $item); 
        break;
    }
}

If you don't want to modify the array while it is being iterated over just find the index then make the modifications.

$foundIndex = false;
foreach($array as $key => $val) {
    if($val->pagerank == 'R') {
        $foundIndex = $key;
        break;
    }
}
if($foundIndex !== false) {
    $item = $array[$foundIndex];
    unset($array[$foundIndex]);
    array_push($array, $item);
}
like image 42
Pitchinnate Avatar answered Oct 01 '22 02:10

Pitchinnate


Something like this?

$var = array(
    'name' => 'thename',
    'title' => 'thetitle',
    'media' => 'themedia'
);

// Remove first element (the name)
$name = array_shift($var);
// Add it on to the end
$var['name'] = $name;

var_dump($var);

/*
array(3) {
  ["title"]=>
  string(8) "thetitle"
  ["media"]=>
  string(8) "themedia"
  ["name"]=>
  string(7) "thename"
}
*/

Ref: http://forums.phpfreaks.com/topic/177878-move-array-index-to-end/

like image 21
Muzafar Ali Avatar answered Oct 01 '22 04:10

Muzafar Ali