简体   繁体   中英

PHP Looping through arrays with 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 3 loops and in the loops are common color names. Using the first for loop I am looping through all the 3 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 foreach loop works but 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 )

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 )

This does use some other PHP functions, but here is one other way to get the keys without using foreach.

<?php

    $value = ["red" => 3, "blue" => 3, "green" => 1, "black" => 1, "purple" => 1, "orange" => 1, "brown" => 1];
    $count = count($value);

    for($i = 0; $i < $count; $i++) {

        if (current($value) > 2) {
            $commonValues[] = key($value);
        }
        next($value);
    }

    print_r($commonValues);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM