1

I am counting the elements of an array and storing the result in an array using array_count_values.

Let's consider this is the output for this instance, which is created from an array, which was in-turn created with the help of explode.

magazine = Array(
    [avatar] => 1
    [essence] => 6
    [pie] => 1
    [multiplex] => 1
    [bill] => 2
    [nice] => 2
    [pie ] => 1
) 

ransom = Array(
    [multiplex] => 1
    [pie] => 2
    [avatar] => 3
    [bill] => 1
    [nice] => 3
    [essence] => 1
)

Now, I want to check if the elements in Array ransom are available in array Magazine. The loop should exit if the element in ransom is not available in magazine. (or) If the element exists, value of that element in ransom cannot be greater than the same element value in magazine.

How can I achieve this? How to use nested foreach in this case? as I cannot use a simple for loop here because of the keys.

$ransom_temp = "avatar essence pie multiplex bill nice essence nice bill essence essence essence essence pie"
$magazine_temp = "multiplex pie pie avatar bill nice nice nice avatar essence avatar"

$magazine = explode(" ",$magazine_temp);
$ransom = explode(" ",$ransom_temp);
$countRan = array_count_values($ransom);
$countMag = array_count_values($magazine);

print_r($countMag);
print "<br>";
print_r($countRan);

if($n > $m){
    print "No";
    return;
}

foreach($countRan as $key1=>$value1){
    foreach($countMag as $key2=>$value2)
    if($key1 != $key2) || $value1 > $value2){
        print "No";
        return;
    }   
}
print "Yes";
0

1 Answer 1

3

You only need one loop:

$ransom_temp = "avatar essence pie multiplex bill nice essence nice bill essence essence essence essence pie"
$magazine_temp = "multiplex pie pie avatar bill nice nice nice avatar essence avatar"

$magazine = explode(" ",$magazine_temp);
$ransom = explode(" ",$ransom_temp);
$countRan = array_count_values($ransom);
$countMag = array_count_values($magazine);

print_r($countMag);
print "<br>";
print_r($countRan);

if(count($countRan) > count($countMag)) {
    print "No";
    return;
}

foreach ($countRan as $key => $value){
    // exit if key not exists in $countMag array
    // or exit if value in $countRan[$key] greater than $countMag[$key]
    if (!array_key_exists($key, $countMag) || $value > $countMag[$key]) {
        print "No";
        return;
    }
}
print "Yes";
1
  • Thank you @hendry fu, that worked like a charm! Thank you. Dec 19, 2017 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.