0

I am stuck. I have 2 arrays that I want to combine, ignoring the empty values, and return a string. Such as:

$Array1 ( [0] => [1] => Monday [2] => Wednesday [3] => Friday [4] => Sunday ) 
$Array2 ( [0] => [1] => 8am [2] => [3] => 10am [4] => [5] => 2pm [6] => [7] => 4pm ) 

to return:

Monday 8am, Wednesday 10am, Friday 2pm, Sunday 4pm

Thanks in advance...

2
  • You can use array_filter(), if you haven't tried. Commented Apr 18, 2012 at 17:38
  • tried array_keys / array_values function to get rid of empty parts? Commented Apr 18, 2012 at 17:45

3 Answers 3

2
$periods = array();
foreach (array_combine(array_filter($Array1), array_filter($Array2)) as $day => $hour) {
  $periods[] = $day . ' ' . $hour;
}
echo implode(', ', $periods);
Sign up to request clarification or add additional context in comments.

Comments

2

It's not entirely clear what format you want the output in, but using array_filter() is the first step:

$a1 = array( null, 'Monday', 'Wednesday', 'Friday', 'Sunday' );
$a2 = array( null, '8am', null, '10am', null, '2pm', null, '4pm' );

$a1 = array_filter($a1);
$a2 = array_filter($a2);

This removes the null entires. You can then use foreach to build your output. For an array of arrays:

$out = array();
foreach ($a1 as $e) $out[] = array($e, array_shift($a2));

For an array of strings:

$out = array();
foreach ($a1 as $e) $out[] = $e.' '.array_shift($a2);

Demo showing both output types: http://codepad.org/ITZJH4RL

1 Comment

array_filter() to remove the null entries was exactly what I was looking for. The rest of my code worked just fine. Thanks!
1

Kind of a dirty way to do it but..

//Your arrays:
$Array1 = array( null , Monday, Wednesday, Friday, Sunday) 
$Array2 = array(null, 8am, null, 10am,null, 2pm, null, 4pm)
$Array3 =();
foreach($Array2 as $key=>$val):
    if($val != ''):
        array_push($Array3, $val);
    endif;
endforeach;

// This assumes you have the same number of values in each array
foreach( $Array1 as $key=>$val):
   $Array1[$key] = $Array1[$key] . " " . $Array3[$key];
endforeach;

var_dump($Array1);

Give it a shot and let me know if you get any errors.

Edit: Turned example arrays into actual arrays instead of just listing them out from the example.

1 Comment

Yea, I know, I was just pulling in his arrays from his example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.