0

How is the way to count length of string in array:

$mainArray = [
    [4],
    [3, 4],
    [2, 30, 43, 65, 53, 634]];

Output desired:

1
1,1
1,2,2,2,2,3

My ideia is change to string use string count function, but have the way to do direct on array?

4
  • You can use $mainArray[i]/10 instead. So if($mainArray[i]/10 ==0) echo 1, if($mainArray[i]/10 >0 && $mainArray[i]/10 <9) echo 2... etc (you can use a switch statement, but the range of integers should be limited!) Commented May 3, 2018 at 0:57
  • 1
    what are you actually doing(just curious)? your last 3 questions have been about the same array but all different? Commented May 3, 2018 at 1:04
  • To long to explain here... @smith Commented May 3, 2018 at 1:07
  • 1
    The answers below are confused about your desired output. Do you want an array of arrays containing the string lengths, or do you want 3 printed lines of comma-separated strings? Your desired output is Unclear. Commented Sep 4, 2021 at 3:51

3 Answers 3

1

PHP has an array_map() which can help you to do this.

function countString($s) {
    return strlen((string)$s);
}

function countArray($arr) {
    return array_map("countString", $arr);
}

$result = array_map("countArray", $mainArray);

Well honestly I do think using two loops would be much easier and clearer...

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_map() with builtin functions implode and strlen:

$mainArray = [
[4],
[3, 4],
[2, 30, 43, 65, 53, 634]];
print_r(array_map(function ($v) { 
                    return implode(',', array_map('strlen', $v));
                  },
                  $mainArray));

Output:

Array
(
    [0] => 1
    [1] => 1,1
    [2] => 1,2,2,2,2,3
)

Comments

0

Try this,

$mainArray = [
[4],
[3, 4],
[2, 30, 43, 65, 53, 634]];
foreach($mainArray as $key => $element):
    foreach($element as $ele):
        $eleString =  countString($ele);
        if(count($element)>1) $eleString .= ',';
            echo $eleString;
    endforeach;
    echo '<br/>';
 endforeach;

 function countString($s) {
    return strlen((string)$s);
 }

1 Comment

This answer is missing its educational explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.