PHP ellipsis using substr and concatenation

If you want to make changes you need to reference & the copy in the foreach.

Example:

foreach($products as &$val) {
                 //  ^ reference
    if(strlen($val['name']) > 5) {
        $val['name'] = substr($val['name'], 0, 5) . ' ...';
    }
}

Or if you are not comfortable this way, could also use the key of the foreach to point it directly to that index.

foreach($products as $key => $val) {
    if(strlen($val['name']) > 5) {
        $products[$key]['name'] = substr($val['name'], 0, 5) . ' ...';
               // ^ use $key
    }
}

And lastly, if you do not want any changes at all (just output echo), then this:

foreach($products as $key => $val) {
    $name = $val['name'];
    if(strlen($name) > 5) {
        $name = substr($name['name'], 0, 5) . '...';
    }
    echo $name; // you forgot to echo
}

Leave a Comment