3

I have an array like,

$words = array ('This', 'is', 'a', '', '', '', 'string');

and I was looking for a function that counts characters of the first two parts, in this case, this and is should be counted . the result for these two will be 5. I know that I can simply do a for, but the problem is I want to count them and if they reach 70 characters or higher then I want to put the rest on a new line.

Any help would be highly appreciated.

Hadi Ahmadi
  • 129
  • 12
  • What have you done so far? By *new line* you want to insert a new array element? – Eddie May 03 '19 at 16:05
  • @Eddie imagine that I have 156 characters in a sentence. I used preg_split to make the words. now I want to count at least 70 characters from that array and put it into a string and do this for the rest until the characters are done – Hadi Ahmadi May 03 '19 at 16:10
  • Please share your expected out in both conditions for proper solution – Rakesh Jakhar May 03 '19 at 16:25

3 Answers3

1

If you only want to count the first 2 then do:

$cnt = strlen($words[0]) + strlen($words[1]);

If you want to add break line after every 70 char you better use full foreach loop with counter as:

$line = 0;
$lines = array();
foreach($words as $word) {
    $line .= " " . $word;
    if (strlen($line) > 70) {
        $lines[] = $line . "\n";
        $line  = '';
    }
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
1

array_map() with strlen will do the trick for you. I guess you know the rest what to do. I hope you can calculate the sum of the first two element of array, if the are equal or higher than 70 then add the rest of the elements on a new line as per your requirements.

<?php
$words = array ('This', 'is', 'a', '', '', '', 'string');
$lengths = array_map('strlen', $words);
print_r($lengths);
?>

Output:

Array ( 
     [0] => 4
     [1] => 2 
     [2] => 1 
     [3] => 0 
     [4] => 0 
     [5] => 0
     [6] => 6 
)
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • @HadiAhmadi glad it helps you some how, I hope you can calculate the sum of the first two element of array, if the are equal or higher to 70 then add the rest on new line as per requirements. Best of luck bro. :) – A l w a y s S u n n y May 03 '19 at 16:20
0

You can get sum of first two string as follows,

$words = array ('This', 'is', 'a', '', '', '', 'string');
// getting length of first two
$lengths = array_sum(array_map('strlen', array_slice($words,0,2)));
// $words = array_filter($words); // if you want to remove empty spaces
$words = implode(" ",$words); // creating a sentence
$newtext = wordwrap($words, 70, "\n"); // or <br /> instead of \n as per your requirement

wordwrap — Wraps a string to a given number of characters
array_filter — Filters elements of an array using a callback function
array_slice — Extract a slice of the array
array_sum — Calculate the sum of values in an array

Rahul
  • 18,271
  • 7
  • 41
  • 60