Search code examples
phpif-statementechofgets

If Condition doesn't work with fgets (STDIN) in PHP


When I use fgets (STDIN) and enter "Yes" in the console, it doesn't return "Works" why? What am I doing wrong?

<?php

$var = fgets(STDIN);
if ($var == "Yes") {
    echo "Works";
}

enter image description here


Solution

  • Input read using fgets includes line-end, trim variable before you compare

    <?php
    
    $var = fgets(STDIN);
    if (trim($var) == "Yes") {
        echo "Works";
    }