0

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 ..)
?>
6
  • 1
    You are already doing the merge, why do it again? If your problem is removing empty cells just do a filter after the merge. Commented Oct 9, 2018 at 15:55
  • The point is that I have the same data in several arrays and I want to arrange it in the way it receives in my code Commented Oct 9, 2018 at 16:00
  • What is your expected output for the example given? a,a,a,..,b,b,b,...c,c,c,...? Commented Oct 9, 2018 at 16:06
  • a,b,c...a,b,c...a,b,c... Commented Oct 9, 2018 at 16:14
  • Duplicate? stackoverflow.com/questions/17386630/… Commented Oct 9, 2018 at 16:20

1 Answer 1

1
$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

Sign up to request clarification or add additional context in comments.

Comments

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.