count of duplicate elements in an array in php - php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc

You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));

foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}

Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/

The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}

$array = array('192', '202', '192', '202');
print_r(array_count_values($array));

$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}

Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;

Check with in_array() function.

Related

Manipulation of php array

I need to create path structure, with the values that I am getting from the array:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
)
[technicalAttribute] => Array
(
[0] => Certificate
[1] => Software
)
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
So, I need to create path that looks like this:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] => TTT 1000 S/Certificate/Spanish
[2] => TTT 1000 S/Software/English
[3] => TTT 1000 S/Software/Spanish
[4] => TTT 1100 S/Certificate/English
[5] => TTT 1100 S/Certificate/Spanish
[6] => TTT 1100 S/Software/English
[7] => TTT 1100 S/Software/Spanish
)
This is a perfect scenario and I was able to solve this with nested foreach:
if (is_array($machineAttributePath))
{
foreach ($machineAttributePath as $machinePath)
{
if (is_array($technicalAttributePath))
{
foreach ($technicalAttributePath as $technicalPath)
{
if (is_array($languageAttributePath))
{
foreach ($languageAttributePath as $languagePath)
{
$multipleMachineValuesPath[] = $machinePath . '/' . $technicalPath . '/' . $languagePath);
}
}
}
}
}
return $multipleMachineValuesPath;
}
But, the problem begins, if the array returns mixed values, sometimes, single value, sometimes array. For example:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
[2] => TTT 1200 S
)
[technicalAttribute] => Certificate
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
Then the array should look like:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] =>TTT 1000 S/Certificate/Spanish
[2] => TTT 1100 S/Certificate/English
[3] => TTT 1100 S/Certificate/Spanish
)
I wrote code, but it is really messy and long and not working properly. I am sure that this could be somehow simplified but I have enough knowledge to solve this. If someone knows how to deal with this situation, please help. Thank you.
You can convert any single value to array just by
(array) $val
In the same time, if $val is already array, it will be not changed
So, you can a little change all foreach
foreach((array) $something....
If you need something simple, you can convert your scalar values to array by writing simple separate function (let name it "force_array"). The function that wraps argument to array if it is not array already.
function force_array($i) { return is_array($i) ? $i : array($i); }
//...
foreach (force_array($machineAttributePath) as $machinePath)
{
foreach (force_array($technicalAttributePath) as $technicalPath)
{
foreach (force_array($languageAttributePath) as $languagePath)
{
$multipleMachineValuesPath[] = $machinePath . '/' . $technicalPath . '/' . $languagePath;
}
}
}
return($multipleMachineValuesPath);
You can do this way also without messing up. Just create the Cartesian of your input array and finally implode the generated array with /. Hope this helps :)
<?php
function cartesian($input) {
$result = array();
while (list($key, $values) = each($input)) {
if (empty($values)) {
continue;
}
if (empty($result)) {
foreach($values as $value) {
$result[] = array($key => $value);
}
}
else {
$append = array();
foreach($result as &$product) {
$product[$key] = array_shift($values);
$copy = $product;
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
array_unshift($values, $product[$key]);
}
$result = array_merge($result, $append);
}
}
return $result;
}
$data = array
(
'machineAttribute' => array
(
'TTT 1000 S',
'TTT 1100 S'
),
'technicalAttribute' => array
(
'Certificate',
'Software'
),
'languageAttribute' => array
(
'English',
'Spanish',
)
);
$combos = cartesian($data);
$final_result = [];
foreach($combos as $combo){
$final_result[] = implode('/',$combo);
}
print_r($final_result);
DEMO:https://3v4l.org/Zh6Ws
This will solve your problem almost.
$arr['machineAttribute'] = (array) $arr['machineAttribute'];
$arr['technicalAttribute'] = (array) $arr['technicalAttribute'];
$arr['languageAttribute'] = (array) $arr['languageAttribute'];
$machCount = count($arr['machineAttribute']);
$techCount = count($arr['technicalAttribute']);
$langCount = count($arr['languageAttribute']);
$attr = [];
for($i=0;$i<$machCount;$i++) {
$attr[0] = $arr['machineAttribute'][$i] ?? "";
for($j=0;$j<$techCount;$j++) {
$attr[1] = $arr['technicalAttribute'][$j] ?? "";
for($k=0;$k<$langCount;$k++) {
$attr[2] = $arr['languageAttribute'][$k] ?? "";
$pathArr[] = implode('/',array_filter($attr));
}
}
}
print_r($pathArr);
This works too!
$results = [[]];
foreach ($arrays as $index => $array) {
$append = [];
foreach ($results as $product) {
foreach ($array as $item) {
$product[$index] = $item;
$append[] = $product;
}
}
$results = $append;
}
print_r(array_map(function($arr){ return implode('/',$arr);},$results));

Remove items from multidimensional array in PHP

I need to remove empty items in a multidimensional array.
Is there a simple way I can remove the empty items easily?
I need to keep only 2010-06 and 2010-07.
Thank you very much!
Array
(
[2010-01] => Array
(
[2010-03] => Array
(
[0] =>
)
[2010-04] => Array
(
[0] =>
)
[2010-06] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
[2010-07] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
)
)
Try this Function. This will solve your issue.
function cleanArray($array)
{
if (is_array($array))
{
foreach ($array as $key => $sub_array)
{
$result = cleanArray($sub_array);
if ($result === false)
{
unset($array[$key]);
}
else
{
$array[$key] = $result;
}
}
}
if (empty($array))
{
return false;
}
return $array;
}
array_filter will not wrok with this array
so try this custom function
<?php
$array =array(
20 => array(
20 => array(
0=> ''
),
10 => array(
0=> 'hey'
)
)
);
function array_remove_empty($arr){
$narr = array();
while(list($key, $val) = each($arr)){
if (is_array($val)){
$val = array_remove_empty($val);
// does the result array contain anything?
if (count($val)!=0){
// yes :-)
$narr[$key] = $val;
}
}
else {
if (trim($val) != ""){
$narr[$key] = $val;
}
}
}
unset($arr);
return $narr;
}
print_r(array_remove_empty($array));
?>
found this answer here

PHP Count Duplicate Total Link

how can i count the total duplicate link in the array?
its similar question here: count of duplicate elements in an array in php
but im not sure how to implement the code on my case.
my server PHP version 5.4
Array
(
[0] => Array
(
[link] => http://myexample.com
[total] => 3
)
[1] => Array
(
[link] => http://myexampledomain.com
[total] => 2
)
[2] => Array
(
[link] => http://myexample.com
[total] => 1
)
)
I am expecting the result to be:
http://myexample.com: 4
http://myotherdomain.com: 2
You can simply use
$result = [];
array_walk($arr, function($v, $k)use(&$result) {
if (isset($result[$v['link']])) {
$result[$v['link']] += $v['total'];
}else{
$result[$v['link']] = $v['total'];
}
});
print_r($result);
Demo
Try below code:
<?php
$array = array(array("link" => "http://myexample.com", "total" => 3), array("link" => "http://myexampledomain.com", "total" => 2), array("link" => "http://myexample.com", "total" => 1));
$res = array();
foreach ($array as $vals) {
if (array_key_exists($vals['link'], $res)) {
$res[$vals['link']]+=$vals['total'];
} else {
$res[$vals['link']]=$vals['total'];
}
}
print_r($res);
?>
You can use this simple logic :
$tempArray = array();
foreach ($array as $value) {
if (!array_key_exists($value['link'],$tempArray) {
$tempArray[$value['link']] = 1;
} else {
$tempArray[$value['link']] = $tempArray['link'] + 1;
}
}
print_r($tempArray);

Edit an array with new values in PHP

I have this array:
Array
(
[datas] => Array
(
[General] => Array
(
[0] => Array
(
[id] => logo
[size] => 10
)
)
[Rooms] => Array
(
[0] => Array
(
[id] => room_1
[size] => 8
)
[1] => Array
(
[id] => room_2
[size] => 8
)
[2] => Array
(
[id] => room_3
[size] => 8
)
)
)
)
I need to update it when I receive some info like this:
$key = 'room_3';
$toChange = '9';
So in my array, I want to change the size of room_3.
I will always edit the same element (i.e. size).
What I tried:
// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
foreach ($datas as $d) {
if (array_search($got, $d)) {
if (in_array($to_find, array_keys($d))) {
return trim($d[$to_find]);
}
}
}
}
But it does not work...
Could you please help me ?
Thanks.
function getDatas($datas, $got, $to_find) {
foreach($datas['datas'] as $key => $rows) {
foreach($rows as $number => $row) {
if($row['id'] == $got) {
// u can return new value
return $row['size'];
// or you can change it and return update array
$datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
return $datas;
}
}
}
}
function changeRoomSize (&$datas, $roomID, $newSize ){
//assuming that you have provided valid data in $datas array
foreach($datas['datas']['Rooms'] as &$room){
if($room['id'] == $roomID){
$room['size'] = $newSize;
break;//you can add break to stop looping after the room size is changed
}
}
}
//--- > define here your array with data
//and then call this function
changeRoomSize($data,"room_3",9);
//print the results
var_dump($data);
It's a 3-dimensional array, if you want to change the value, do like this:
$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
if ($v2['id'] == $key)) {
$rooms[$k1][$k2]['size'] = $toChange;
}
}
return $rooms;
}
print_r($array);

Find value and key in multidimensional array

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.
Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}
You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}
First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.
I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"
This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>
Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");
function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

Categories