Wojtek
Wojtek

Reputation: 67

Combine data from several array to one array

I wrote a script that combines the results equally from several arrays. The script works well, but I would like to do it more easily. My knowledge of php programming is poor. I have a question for experienced programmers, do you have any idea how can I get the same result using a better solution?

My code:

<?php
$a = array('a','a','a','a','a','a','a','a');
$b = array('b','b','b','b','b','b','b','b');
$c = array('c','c','c','c','c','c','c','c');

$count = count(array_merge($a, $b, $c));

$results = array();
for ($i=1; $i<$count; $i++){

    if (isset($a[$i]) && !empty($a[$i])){ $results[] = $a[$i]; } 
    if (isset($b[$i]) && !empty($b[$i])){ $results[] = $b[$i]; } 
    if (isset($c[$i]) && !empty($c[$i])){ $results[] = $c[$i]; } 
}

print_r($results); // array(a, b, c, a, b, c ..)
?>

Upvotes: 0

Views: 48

Answers (1)

Cyrus G
Cyrus G

Reputation: 21

$a = array('a','a','a','a','a','a','a','a');
$b = array('b','b','b','b','b','b','b','b');
$c = array('c','c','c','c','c','c','c','c');


for ($i=0; $i < max(count($a), count($b), count($c)) ; $i++) {
    foreach (array('a', 'b', 'c') as $l) {
        if (!isset($$l[$i]) || empty($$l[$i])) {continue; };
        $results[] = $$l[$i];
    };
}; 


print_r($results);

Please note that in your code, you started with $i = 1, whereas you probably wanted to start at $i = 0 (the first entry of an array is 0, not 1).

The code could be further improved depending on the requirements: if you only have 3 arrays, and it's not super important, that should do it

Upvotes: 1

Related Questions