-3

Possible Duplicate:
Combing 3 arrays into one array

I have the following arrays:

$front = array("front_first","front_second");
$back = array("back_first", "back_second", "back_third","back_fourth");

what I'm trying to do is merge them so an output like this would result:

$final = array(
    "back_first",
    "front_first",
    "back_second",
    "front_second",
    "back_third",
    "front_second",
    "back_fourth",
    "front_second"
);

How can I have it repeat the last value in the shortest array so that it can combine into one $final[] with no empty values?.

Community
  • 1
  • 1
thindery
  • 1,164
  • 4
  • 23
  • 40

3 Answers3

0

php's array_merge

$final = array_merge($front, $back);

and maybe a combination with array_pad?

$front = array_pad($front, count($back)-1, 'second_front');
 $final = array_merge($front, $back);
Asgaroth
  • 4,274
  • 3
  • 20
  • 36
0

The first bit is easy, just use array_merge() to construct your combined array.

The second bit requires arbitrary sorting and therefore will require use of usort() to sort the array according to rules you implement in the callback function.

Is the order really important?

GordonM
  • 31,179
  • 15
  • 87
  • 129
0

Working Codepad - bgIYz9iw

$final = array();
for( $i = 0; $i < 4; $i++ ) {
  if( $i > 1 ) {
    $final[] = $back[$i];
    $final[] = $front[1];
  }
  else {
    $final[] = $back[$i];
    $final[] = $front[$i];
  }
}
hjpotter92
  • 78,589
  • 36
  • 144
  • 183