Home > Software design >  PHP - how can I get the number of characters in an array value?
PHP - how can I get the number of characters in an array value?

Time:10-07

I'm trying to figure out how to get a character count from a group of values in an array, so I can test it in an if statement.

Best if I give you an example of what I want to do:


//sample

$content = '<p>this is p 1</p><p>this is p 2</p><p>this is p 3</p><p>this is p 4</p><p>$test</p>';
$parts = explode('</p>',$content);

foreach ($parts as $key => $value) {
  $test = count_chars($value[0]   $value[1]   $value[2]);

  if ($test > 40) {
    echo 'Yep, there are '.$test.' characters in the first three paragraphs<br />';
  }
  else { 
    echo 'Nope. There are '.$test.' characters in the first three paragraphs<br />'; 
  }
}

I don't work with arrays much, so not sure how to do this. Right now $test just gives me 'array'.

And I know this is going to repeat the same string, this is not the final product, stripped out as many details as I could so we could focus on the situation I'm stuck on :)

CodePudding user response:

If you want to count all character use strlen() insted of count_chars() like this

$test = strlen($value[0].$value[1].$value[2]);

count_chars() function will returns information about characters used in a string (for example, how many times an ASCII character occurs in a string, or which characters that have been used or not been used in a string) enter image description here

You can call it with different mode to get a string as a result. But based on what you described, this is not what you want. You will need to call strlen instead:

$totalLength = $myStringArray[0];
for ($index = 1; $index < count($myStringArray); $index  ) {
    $totalLength  = $myStringArray[$index];
}

as about the explode, you are removing the </p> from the string, which I suppose is your actual goal. But you still left <p> inside the string. You will need to remove it too if you want to exclude it. You can use str_replace for that purpose, like:

$length = str_replace('<p>', '', str_replace('</p>', '', $content));
  •  Tags:  
  • php
  • Related