我想从循环中创建数组并从该数组中计算相同的值

I want create array from looping.

I have tried using array_count_values() for count the array element, but variable from looping not read as array.

it's my code

$var_from_loop = "true,true,true,false,false";

I expect the output of:

true = 3
false = 2

Use explode (doc) to convert the string to array by , and then use array-count-values:

$var_from_loop = "true,true,true,false,false";
$arr = explode("," , $var_from_loop);
print_r(array_count_values($arr));

Live example: https://3v4l.org/FHrqi

Steps for approach 1:

1) You can first convert the string to array by explode() by comma(,).

You will get the following array:

Array
(
    [0] => true // 1st true
    [1] => true // 2nd true
    [2] => true // 3rd true 
    [3] => false // 1st false
    [4] => false // 2nd false
)

2) You will get an array containing 3 true and 2 false values (elements).

3) Then count how many times a values comes in array using array_count_values().

<?php
$var_from_loop = "true,true,true,false,false";
$arr = explode(',', $var_from_loop);
echo '<pre>';
print_r(array_count_values($arr));
echo '</pre>';

Output:

Array
(
    [true] => 3
    [false] => 2
)

Working example:

Steps for approach 2 (only 3 lines of code):

You can even use substr_count():

$var_from_loop = "true,true,true,false,false";
echo 'TRUE: '.substr_count($var_from_loop, 'true');
echo '<br/>FALSE: '.substr_count($var_from_loop, 'false');

Output:

TRUE: 3
FALSE: 2

Use explode and array count function

$var_from_loop = "true,true,true,false,false";
print_r(array_count_values(explode(",",$var_from_loop)));

output:-

Array
(
    [true] => 3
    [false] => 2
)