Search code examples
phphtmlmysqldatabasemaxlength

PHP - If variable's character is number then do something


I created a PHP page that show names from a table, there is some names is too long, I want to make if $name is 12 characters then replace what after 12 characters with ... this is my code

$query= mysql_query("SELECT * FROM `table`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
    $num = mysql_num_rows($query);
    $name= $arr['name'];
    echo '</br>';
    echo $name;
}

How can I do it?


Solution

  • Try:

    $name = (strlen($arr['name']) > 12) ? substr($arr['name'],0,12) . "..." : $arr['name'];
    

    This is a conditional assignment. If $arr['name'] is greater than 12 characters, then it truncates it to 12 characters and adds "...". Otherwise, it uses the full name.