Daniel C
Daniel C

Reputation: 627

How to limit the number of characters printed for a particular array key

The script below prints a table based on a MySQL query using PDO:

<?php  
//PDO start
$dbh = new PDO(...);
$stmt = $dbh->prepare($query);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$arrValues = $stmt->fetchAll();   

//create table
print "<table> \n";
print "<tr>\n";

//add table headers
foreach ($arrValues[0] as $key => $useless){ 
print "<th>$key</th>";
}
print "</tr>";

//add table rows
foreach ($arrValues as $row){
    print "<tr>";
    foreach ($row as $key => $val){
        print "<td>$val</td>";

    }
print "</tr>\n";
}
//close the table
print "</table>\n";
?>

This works fine, but one of the keys in the array contains some paragraph text that is very long. An example vardump is below:

array
  0 => 
    array
      'Name' => string 'John' (length=5)
      'Day' => string 'Monday' (length=6)
      'Task' => string 'This is a really long task description that is too long to be printed in the table' (length=82)
      'Total Hours' => string '5.00' (length=4)

I would like to have the 'Task' key only print the first 50 characters with a '...' at the end. I'm not sure how to add that condition within the foreach loop. Any tips would be appreciated.

Upvotes: 0

Views: 245

Answers (1)

Waleed Khan
Waleed Khan

Reputation: 11467

Add a conditional here:

foreach ($row as $key => $val){
    print "<td>$val</td>";
}

You'll check to see if it's longer than fifty characters:

$truncate_keys = array("task");
foreach ($row as $key => $val){
    if (strlen($val) > 50 && in_array($key, $truncate_keys)) {
        print "<td>" . substr($val, 0, 50) . "...</td>";
    } else {
        print "<td>$val</td>";
    }
}

Be warned: this approach will cut off in the middle of words. This problem has already been solved, and in better ways; for example, this CodeIgniter helper has a solution that allegedly keeps words intact.

Upvotes: 2

Related Questions