Search code examples
phpsubstr

PHP: Substr() returns empty string


I want to get the first letters of a string, but every time its giving me a empty result. The string is following.

080521234567890

Here is my code:

    <?php
        if ($_GET['test1']) 
        {
            echo "<table border =0>";
            $parsing = "080521234567890";
            echo "<tr>";
            if ($p1 = substr($parsing,0,1))    
                {
                    echo "<td><strong>Version Format n1</strong></td>";
                    echo "<td>: $p1</td"; 
                }
            echo "</tr>";
        echo "</table>";
        }
    ?>

In the line echo ": $p1</td"; return empty value. enter image description here


Solution

  • The issue doesn't come from the substring function, but from your condition.

    This code is working fine :

    <?php
    
        echo "<table border =0>";
    
            $parsing = "080521234567890";
    
            echo "<tr>";
    
                $p1 = substr($parsing,0,1);  
    
                echo "<td><strong>Version Format n1</strong></td>";
                echo "<td>: $p1</td>"; //returns 0
    
            echo "</tr>";
    
        echo "</table>";
        
    ?>
    

    Referring to yours, your if statement uses the assignment operator (=) instead of comparison (==) and returns 0 because it is the first character of your string $parsing. So you do not execute statements inside your condition block.