skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search