Reputation: 23
Im working on something and i need to shift an array with ID's so the ID(person) cant get his own ID unless the "game" is over.
So i got this:
$array = array(
"2" => "2",
"3" => "3",
"6" => "6",
"8" => "8",
"12" => "12",
);
And i want it this way:
$array = array(
"2" => "3",
"3" => "6",
"6" => "8",
"8" => "12",
"12" => "2",
);
I'm not a real php hero and the internet isn't helping so far :)
Thx in advance!
Upvotes: 0
Views: 102
Reputation: 23
So after long trying and getting some help from an old friend this is the final result:
$prev = null;
$firstIndex = null;
foreach ($userArr as $i => $user) {
if (is_null($prev)) {
$firstIndex = $i;
$prev = $user;
continue;
}
$userArr[$i] = $prev;
$prev = $user;
}
$userArr[$firstIndex] = $prev;
Upvotes: 0
Reputation: 7485
<?php
$in = array(
"2" => "2",
"3" => "3",
"6" => "6",
"8" => "8",
"12" => "12",
);
$out = array(
"2" => "3",
"3" => "6",
"6" => "8",
"8" => "12",
"12" => "2",
);
function transpose_values(array $in) {
$values = array_values($in);
$first = array_shift($values);
$first && array_push($values, $first);
$out = array_combine($in, $values);
return $out;
}
assert($out == transpose_values($in));
Upvotes: 1
Reputation: 1746
Without knowing what the array's values are supposed to represent, it's a little heard to tell what you're actually trying to do. The way it looks is that a person's (user's?) ID will represent something entirely different given some particular scenario.
Taking your question at face-value therefore, you need a new array, with the values of the old one to be those values, one-position ahead of where they were originally. Use of reset() and next() are the keys here:
$newArray = [];
$firstVal = reset($array);
$i=0;
foreach($array as $key => $val) {
++$i;
// Deal with the last array-element to be given the first's value
if(count($newArray) === $i) {
$newArray[$key] = $firstVal;
} else {
$newArray[$key] = next($array);
}
}
Upvotes: 0