-2
    foreach($products as $val)
    {
        $name = $val["name"];

        if(strlen($name) > 5){
             $name = substr($name,0,5) . '..';
        }

}

I have a list of string, and I want to add dot dot at the end of it using PHP, but above code return 0?

Kevin
  • 41,694
  • 12
  • 53
  • 70

2 Answers2

3

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
}
Kevin
  • 41,694
  • 12
  • 53
  • 70
1

your question is a bit unclear as to where you are stuck.

If you want to modify your $products array, then Ghost offered you one solution.

If you simply want an array of shortened product names, I would store them in a new array since you might need the full names later.

$shortNames = array();
foreach($products as $val)
{
    $name = $val["name"];

    if(strlen($name) > 5){
         $name = substr($name,0,5) . '..';
    }
    $shortNames[] = $name;

}

You wrote

but above code return 0

if this code is inside a function, maybe you simple missed to return the result? for example with my code, put return $shortNames; at the end of the function

cypherabe
  • 2,562
  • 1
  • 20
  • 35