I have the following array:
$myarray = Array("2011-06-21", "2011-06-22", "2011-06-22", "2011-06-23", "2011-06-23", "2011-06-24", "2011-06-24", "2011-06-25", "2011-06-25", "2011-06-26");
var_dump($myarray);
Result:
Array (
[0] => 2011-06-21
[1] => 2011-06-22
[2] => 2011-06-22
[3] => 2011-06-23
[4] => 2011-06-23
[5] => 2011-06-24
[6] => 2011-06-24
[7] => 2011-06-25
[8] => 2011-06-25
[9] => 2011-06-26
)
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
Code Inspection: Duplicate array keysReports duplicate keys in array declarations. If multiple elements in the array declaration use the same key, only the last one will be used, and all others will be overwritten.
To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
I'll answer the second question first. You want to use array_keys
with the "search_value" specified.
$keys = array_keys($array, "2011-06-29")
In the example below, $duplicates
will contain the duplication values while $result
will contain ones that are not duplicates. To get the keys, simply use array_keys
.
<?php
$array = array(
'a',
'a',
'b',
'c',
'd'
);
// Unique values
$unique = array_unique($array);
// Duplicates
$duplicates = array_diff_assoc($array, $unique);
// Unique values
$result = array_diff($unique, $duplicates);
// Get the unique keys
$unique_keys = array_keys($result);
// Get duplicate keys
$duplicate_keys = array_keys(array_intersect($array, $duplicates));
Result:
// $duplicates
Array
(
[1] => a
)
// $result
Array
(
[2] => b
[3] => c
[4] => d
)
// $unique_keys
Array
(
[0] => 2
[1] => 3
[2] => 4
)
// $duplicate_keys
Array
(
[0] => 0
[1] => 1
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With