0

I have the following code in a Laravel 5.4 Blade view:

@php($strVal = $character->Strength)

                        @php($strMod = 0)

                        <?php 
                            if ($strVal == 10 || 11) {
                                $strMod = 0;
                            } elseif ($strVal == 12 || 13) {
                                $strMod = 1;
                            } elseif ($strVal == 14) {
                                $strMod = 2;
                            } else {
                                $strMod = 2;
                            }


                        ?>

It takes data from a MySQL table. $strVal is an int from the table. The code creates a var called $strMod and goes through a number of if/elseif statements to see what it will be equal to.

It's shown on a webpage as follows:

<div class="huge charMod">+{{$strMod}}</div>

My issue is that it displays as "+0" no matter what strVar equals. strVar is working fine, I can pull it from the DB and display it via {{ $strVal }} but strMod refuses to take a value other than 0.

2 Answers 2

2

$strVal == 10 || 11 will always return true

Because that's not how comparisons work in PHP. The == operator has a higher precedence than || operator, so it will be performed first.

It means that $strVal == 10 || 11 gets turned into false || 11 .. which is true.

Instead of that code, I would recommend:

$map = [
    10 => 0,
    11 => 0,
    12 => 1,
    13 => 1, 
    // you dont actually need 14, because default value is aready 2
];

$result = 2;

if (array_key_exists($strVal, $map)) {
    $result = $map[$strVal];
}

$strVal = $result;

Or, if you are using PHP 7.0+ it all can actually be written as:

$map = [10 => 0, 11 => 0, 12 => 1, 13 => 1];
$strVal = $map[$strVal] ?? 2;
Sign up to request clarification or add additional context in comments.

Comments

0

You need to change your if checks to

if ($strVal == 10 || $strVal == 11) {
    $strMod = 0;
} elseif ($strVal == 12 || $strVal == 13) {
    $strMod = 1;
} elseif ($strVal == 14) {
    $strMod = 2;
} else {
    $strMod = 2;
}

if ($strVal == 10 || 11) will always return true. If you want to check two values you need to specify that by using the variable == value again as in the example above.

1 Comment

You, sir, are a wizard. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.