Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat items in a php array until they match the count of another array

Tags:

arrays

php

I've created two arrays from strings using explode() one called $labels and the other called $colors. What I'd like to do is check the count of the items in $labels and if there are less items in $colors I'd like the values of the $colors array to be repeated until the count matches. If there are more items in $colors than in $labels I'd like to reduce remove items from the $colors array until it matches the number of items in $labels.

I assume I can use count() or array_legnth() in a conditional to compare the number of items between the two arrays and that I'm going to have to use some kind of while loop but really not sure how to get started.

Is there a better way or function I should use to compare the two arrays? And how would I go about repeating or deleting the items in the second array so that I land up with the same number of items in each?

like image 793
bigmadwolf Avatar asked Dec 18 '25 05:12

bigmadwolf


1 Answers

Here is what you can do :

// the two arrays
$labels = array('a', 'b', 'c', 'd', 'e');
$colors = array(1, 2, 3, 4);


// only if the two arrays don't hold the same number of elements
if (count($labels) != count($colors)) {
    // handle if $colors is less than $labels
    while (count($colors) < count($labels)) {
        // NOTE : we are using array_values($colors) to make sure we use 
        //        numeric keys. 
        //        See http://php.net/manual/en/function.array-merge.php)
        $colors = array_merge($colors, array_values($colors));
    }

    // handle if $colors has more than $labels
    $colors = array_slice($colors, 0, count($labels));
}

// your resulting arrays    
var_dump($labels, $colors);

Put that into an utility function and you will be good to go.

like image 76
Yanick Rochon Avatar answered Dec 19 '25 19:12

Yanick Rochon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!