Howard
Howard

Reputation: 3758

Is there an elegant way to start a foreach from the second index and then do the rest?

If I have the following:

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $v) {
    echo $v;
}

How can I make it output:

2, 1, 3, 17

Upvotes: 2

Views: 90

Answers (3)

mhall
mhall

Reputation: 3701

Quoting the PHP Manual on Language Operators:

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

$b = array_values($a);
echo implode(', ', array($b[1], $b[0]) + $b), PHP_EOL;

Output:

2, 1, 3, 17

Upvotes: 2

Xeridea
Xeridea

Reputation: 1136

$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
foreach (array_slice($values, 2) as $v){
    echo "$v, "
}

If you care about last comma...

$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
$lastIndex = count($values) - 1;

foreach (array_slice($values, 2) as $k => $v){
    echo $v;
    if ($k != $lastIndex){
        echo ", ";
    }
}

Upvotes: 1

reallyxloco
reallyxloco

Reputation: 114

You could probably do something like:

<?php

$my_array = array(...); 

$keys = array_keys($my_array);
$second_key = $keys[1]; // if your array can be whatever size, probably want to check that first

echo $my_array[$second_key];

foreach ($my_array as $key => $value) {
  if ($key == $second_key) {
    continue;
  }

  echo $value;
}

?>

Upvotes: 0

Related Questions