0

Hello I am just starting my adventure with coding and I have a question regarding that.

$element are numbers: 1,5,10,20.

$liczba = tab[0] - then $liczba value is 1.

So if $element>$liczba, and liczba is 1, then tab[0] - which is 1 shouldn't fit that criteria.

So why when I echo $liczba I get all elements with 1?

And second question. Why when I echo $liczba beyond [] brackets I get only 20 result, not 1(which shouldn't be here),5,10,20?

Answer is probably obvious, but I can't figure it out.

    <?php

$tab = array("1", "5", "10", "20");
$liczba = $tab[0];

foreach ($tab as $element)
{
    if($element>$liczba)
    $liczba = $element;
      echo $liczba; 
}
  echo $liczba; 
?>
0

1 Answer 1

1

You have forgotten to put braces {} after your if statement, meaning the comparison is unused so it is displaying all data.

$tab = array(1, 5, 10, 20);

foreach ($tab as $element) {
    if ($element > $tab[0]) {
        echo $element . ", ";
    }
}

I have also simplified your code by removing unnecessary variables.

Best practice: I believe you should use a type that fits what you are comparing:

$tab = array("1", "5", "10", "20");

This will improve code readability.

$tab = array(1, 5, 10, 20);
Sign up to request clarification or add additional context in comments.

2 Comments

Numeric comparisons will work just fine with strings or integers. PHP is a loosely typed language.
But still after I echo $element variable, outside foreach function I always get 20 Instead of 5.10.20?

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.