0

I am pulling some data from a JSON source in a PHP loop and want to character limit/restrict one of the data nodes I render. I have used:

<?php echo $character['description'] = substr($character['description'],0,250).'...'; ?>

But this means each time the loop is called and the next set of results are echoed - the number of limited characters increases... Is there a way to get ALL 'description' strings to be capped to 250 characters with a '...' added after?

loop code is:

<?php foreach ($characters as $character) : ?>

<p class="description"><?php echo $character['description']; ?></p>

<?php endforeach; ?>
dubbs
  • 1,167
  • 2
  • 13
  • 34
  • Possible duplicate of [Truncating Text in PHP?](https://stackoverflow.com/questions/9219795/truncating-text-in-php) – Reactgular May 31 '18 at 14:16
  • are you saying that the total amount of the descriptions need to be up to 250 or that each has a lenght of 250? – Lelio Faieta May 31 '18 at 14:27

1 Answers1

0

EDIT: I cannot see why this wouldn't work:

<?php foreach ($characters as $character) : ?>

<p class="description"><?php echo substr($character['description'], 0, 250); ?></p>

<?php endforeach; ?>

?

cjs1978
  • 477
  • 3
  • 7
  • Basically, the $character['description'] array value should be reset in each iteration of the loop. So I cannot see why my edited version wouldn't work. – cjs1978 May 31 '18 at 14:23
  • What I mean is that $character always contains the value at the current index of $characters (which is being iterated in the foreach loop). So that should neither "get more or less" during the looping. – cjs1978 May 31 '18 at 14:25
  • OK.. your code works fine... issue was some nested HTML markup inside the fetched 'description' string from JSON... that was messing things up! – dubbs May 31 '18 at 14:35
  • Great to hear :) – cjs1978 May 31 '18 at 14:37