2

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
1
  • can you help me to change it to array ? Commented Apr 4, 2019 at 6:52

3 Answers 3

4

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

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

1 Comment

wait ... I've tried it and it didn't work. But now it working.. thank @dWinder
4

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

Comments

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
)

Comments

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.