0

My old array

array:7 [
  0 => "22-Feb-2017"
  1 => "22-Feb-2017"
  2 => "22-Feb-2017"
  3 => "27-May-2015"
  4 => "10-May-2015"
  5 => "10-May-2015"
  6 => "08-May-2015"
]

I want new array as

array:7 [
  22-Feb-2017 => "3"
  27-May-2015 => "1"
  10-May-2015 => "2"
  08-May-2015 => "1"
]

6 Answers 6

6

Just try using array_count_values.The array_count_values() function counts all the values of an array.

<?php
$dates = [
    0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015",
];
$final_array = array_count_values($dates);
print_r($final_array);

OUTPUT

Array
(
    [22-Feb-2017] => 3
    [27-May-2015] => 1
    [10-May-2015] => 2
    [08-May-2015] => 1
)
Sign up to request clarification or add additional context in comments.

1 Comment

thasnk!! This Works for me
5

Not sure if you're looking for something like this

http://php.net/manual/en/function.array-count-values.php

Comments

2

Please check the below output :

 $a=array(0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015");

    ///array_count_values counts the same values count////
    $new_array = array_count_values($a);
/// now let's interchange the keys and values////
    foreach($new_array as $key=>$value){
        $out[$value] = $key;
    }

    print_r($out);

1 Comment

Thanks!! This Works
1

One way for going about it:

$dates = [
    0 => "22-Feb-2017",
    1 => "22-Feb-2017",
    2 => "22-Feb-2017",
    3 => "27-May-2015",
    4 => "10-May-2015",
    5 => "10-May-2015",
    6 => "08-May-2015",
];

$result = [];

foreach ($dates as $date) {
    $result[$date] = array_key_exists($date, $result) ? $result[$date] + 1 : 1;
}

print_r($result);

1 Comment

Thanks!! this Works
1

This is what you need exactly:

  <?php
    $old_array=array(
        0 => "22-Feb-2017",
        1 => "22-Feb-2017",
        2 => "22-Feb-2017",
        3 => "27-May-2015",
        4 => "10-May-2015",
        5 => "10-May-2015",
        6 => "08-May-2015");

        /*
        Counting the occurances of value & storing it in a new array in the format:
        array("22-Feb-2017"=>3, "27-May-2015"=>2, .........)
        */
        $new_array = array_count_values($a);

        print_r($new_array);

        echo $new_array["22-Feb-2017"];
    ?>

Comments

1
$data=[0 => "22-Feb-2017",1 => "22-Feb-2017",2 => "22-Feb-2017",3 => "27-May-2015",4 => "10-May-2015",5 => "10-May-2015",6 => "08-May-2015"];
$a=array_count_values($data);

var_dump($a);

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.