Skip to content
Advertisement

PHP: For loop, how do I set a variable as a maximum?

I am trying to be able to make a loop that lets me place stars on a website, to show a rating (1 to 5) on the website, that you can put down with fields. However, I do not know how to convert the field correctly.

I am using WordPress with Custom Field types, this is were I define the variable.

I have a variable that I get from somewhere else, and I have tried the following two ways:

<?php
    $star = intval(the_field('rating'));
    for ($i=0; $i < $star; $i++){
        intval(the_field('rating'));
    }
?>

and the second one:

<?php
    $star = number_format(the_field('rating');
    for ($i=0; $i < $star; $i++){
        number_format(the_field('rating'));
    }
?>

Thank you very much for you help in advance.

Advertisement

Answer

First the_field echos the value, you need get_field to return the value. Then just repeat whatever string you’re using to display a star or empty star:

$stars = get_field('rating');
echo str_repeat('*', $stars) . str_repeat('O', 5-$stars);

With a loop just check if your counter is less than or equal to the star rating:

$stars = get_field('rating');

for ($i=1; $i <= 5; $i++){
    echo ($i <= $stars) ? "*" : "O";
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement