Search code examples
phparraysloopsfor-loopforeach

PHP Looping through arrays with a 'for' loop


I am getting more practice with using for loops to loop through arrays, and have a question that I can't figure out thus far.

I have three loops and in the loops are common color names. Using the first for loop, I am looping through all the three loops and finding the common color name, this works fine.

The second part is where I am stumped on how to do this, how to assign the common values array into another array to just show those common values.

I know I can use a foreach loop that does the trick as shown below, but I am trying to see how to do this with a for loop instead.

How can I do this? (without using array_intersect)

Code (this loops through all arrays and gives me the common values):

$array1 = ['red', 'blue', 'green'];
$array2 = ['black', 'blue', 'purple', 'red'];
$array3 = ['red', 'blue', 'orange', 'brown'];

$value = [];

$array_total = array_merge($array1, $array2, $array3);

$array_length = count($array_total);

for ($i = 0; $i < $array_length; $i++) {
    if (!isset($value[$array_total[$i]])) {
        $value[$array_total[$i]] = 0;
    }

    $a = $value[$array_total[$i]]++;
}
//print_r($value); -- Array ( [red] => 3 [blue] => 3 [green] => 1 [black] => 1 [purple] => 1 [orange] => 1 [brown] => 1 )

Using a foreach loop works, but I want to learn how to do it with a for loop:

$commonValues = [];

foreach ($value as $values => $count) {
    if ($count > 2) {
        $commonValues[] = $values;
    }
}
print_r($commonValues); -- Array ( [0] => red [1] => blue )

Solution

  • This should work for you:

    Just use array_keys() to get an array with which you can access your associative array with numerical keys

    <?php
    
        $value = ["red" => 3, "blue" => 3, "green" => 1, "black" => 1, "purple" => 1, "orange" => 1, "brown" => 1];
        $count = count($value);
        $keys = array_keys($value);
    
        for($i = 0; $i < $count; $i++) {
            if ($value[$keys[$i]] > 2) {
                $commonValues[] = $keys[$i];
            }
        }
    
        print_r($commonValues);
    
    ?>
    

    output:

    Array ( [0] => red [1] => blue )