Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading