Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php foreach set a limit on the output of characters in a string field

Let’s say I have a php loop on output

<?php foreach ($items as $item) { ?>
  <div class="title"><?= $item->title ?></div>
  <div class="description"><?= $item->description?></div>
<?php } ?>

As a result, in html I get the following

<div class="title">What is Lorem Ipsum?</div>
<div class="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

Now my description field has 566 characters

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I make the maximum number of characters for the description field on the php side so that the maximum number of characters for the description field is, say, 230 and it is displayed like this with three dots at the end?

<div class="title">What is Lorem Ipsum?</div>
<div class="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type...</div>

>Solution :

You can do this by checking the length and using a substring when the description exceeds the length you set.

<div class="description">
    <?php echo (strlen($item->description) > 230) ? substr($item->description, 0, 230) . '...' : $item->description ?>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading