Search code examples
phpsubstr

substr inside php echo


In my code below substr function is not working, why it is so and how to make it work.

<?php
// some code

echo "
<h2>".$row['title']."</h2>
<p> substr( ".$row['body'].",0,300) ....</p>
<p>".$row['posted']."</p>";

Solution

  • In my code below substr function is not working, why it is so?

    • Its because its been treated as string literal and not a function

    How to make it work?

    • You need to take care about string concatenation or simply store the value of substr within a variable.

    Example:

    $substr_value = substr($row['body'],0,300);
    echo "
    <h2>{$row['title']}</h2>
    <p>$substr_value</p>
    <p>{$row['posted']}</p>";