Home > Mobile >  PHP: Substr() returns empty string
PHP: Substr() returns empty string

Time:06-30

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

CodePudding user response:

If you are trying to compare, you need to update your condition, instead of $p1 = substr($parsing,0,1), you need to make $p1 == substr($parsing,0,1), and if you want strict comparison, you can use $p1 === substr($parsing,0,1) as well.

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

Else, if you are trying to assign value, you need to get rid of if block and do something like this

$p1 = substr($parsing,0,1));    
echo "<td><strong>Version Format n1</strong></td>";
echo "<td>: $p1</td"; 

CodePudding user response:

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.

  • Related