Home > Blockchain >  comparing a value from an array with an int
comparing a value from an array with an int

Time:11-05

i got an array like this

$ratings =
[
   [   'text' => 'bla',
       'author' => 'Ute U.',
       'stars' => 2
   ],
   [   'text' => 'bla2',
       'author' => 'Ute a.',
       'stars' => 4
   ]
]

Its obvious that the value behind 'stars' is an integer. But how do I compare that value with any number? What i tried, and doesn't work is

foreach ($ratings as $rating)
{
        
        if ($rating['stars'] == 5)
        {
            $showRatings[] = $rating;
        }
}

The assigning line isnt the problem, i am sure of that since all other code not regarding the comparism works with this line.

I ofc also tried 12 other solution from various sites.. it never ever works..

Please help a brother out here.

CodePudding user response:

your code is fine the value is never 5 in your example so the condition is never true.

CodePudding user response:

This should work... I've tried it and its working fine for me.

$ratings =
[
   [   'text' => 'bla',
       'author' => 'Ute U.',
       'stars' => 4
   ],
   [   'text' => 'bla2',
       'author' => 'Ute a.',
       'stars' => 5
   ]
];

$showRatings = array();

foreach ($ratings as $rating)
{
    foreach($rating as $key=>$value){
        if($key=='stars' && $value==5){
            $showRatings[] = $rating;
        }
    }
}

print_r($showRatings);
  •  Tags:  
  • php
  • Related