How to find duplicated values in PHP arrays? - php

I have an array like this
$a=array(0=>1,1=>1,2=>5,3=>5,4=>10)
Now I want to find out the duplicate values and add those in to an array like this:
array_push($arrayOfones,$a['0'],$a['1'];
array_push($arrayOfFive,$a['2'],$a['5'];

You could take a look at array_count_values
$ret = array_count_values($a);
// get the duplicate values
$ret = array_filter($ret, function ($var) {
return $var > 1;
});
array_walk($ret, function(&$var, $key) {
$var = array_fill(0, $var, $key);
});
var_dump($ret); // $ret[1] is $arrayOfOnes, $ret[5] is $arrayOfFive

little simpler with no array functions other than count():
foreach($a as $key=>$value){
$ip[$value][] = $key;
}
foreach($ip as $key=>$inner_arr){
if(count($inner_arr) > 1)
$dup[$key] = $inner_arr ;
}

$a=array(0=>1,1=>1,2=>5,3=>5,4=>10);
$c=0;
foreach ($a as $key => $row) {
if (!isset($rs[$row])) {
$rs[$row][$key]= $key;
$c = 1;
$res[$row]['count'] = $c;
$res[$row]['values'][$key] = $key;
}
else {
$res[$row]['count']++;
$res[$row]['values'][$key] = $key;
}
}

Related

PHP How to merge array element with next while maintaining order?

$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);

Make my array pretty

I have an array wich is structured like this
foo = stuff we don't care for this example
foo1_value
foo1_label
foo1_unit
foo2_value
foo3_label
foo3_value
Can you figure out a fast way to make it look like that ?
foo
foo1
value
label
unit
foo2
value
foo3
value
label
I'm actually trying with something like this :
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
list($name, $subName) = explode('_', $key);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});
echo '<pre>';
print_r($nice_array);
echo '</pre>';
This is working I'll just have to reflect on the foo_foo_label thing and it's all good
You could use explode on the array keys, something like this:
$newArray = array();
foreach ( $array as $key => $value )
{
$parts = explode('_', $key);
$newArray[$parts[0]][$parts[1]] = $value;
}
Edit: update as detailed in comments. Will handle your foo_foo_value case as well as foo and foo_foo. There's really no reason to use array_walk if you're only passing the results off to a second array.
$newArray = array();
foreach ( $array as $key => $value ) {
if ( preg_match('/_(label|value|unit)$/', $key) === 0 ) {
$newArray[$key] = $value;
continue;
}
$pos = strrpos($key, '_');
$newArray[substr($key, 0, $pos)][substr($key, $pos+1, strlen($key))] = $value;
}
What you can do is loop over the array, and split (explode()) each key on _ to build your new array.
$newArray = array();
foreach($oldArray as $key=>$value){
list($name, $subName) = explode('_', $key);
if($subName !== NULL){
if(!isset($newArray[$name])){
$newArray[$name] = array();
}
$newArray[$name][$subName] = $value;
}
else{
$newArray[$name] = $value;
}
}
$nice_array = array();
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
$tname = preg_split("/_label$|_value$|_unit$|_libelle$/",$key);
$name = $tname[0];
$subName = substr($match[0],1);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});

How to generate permutaion and combination result

i have this array
$dataArray = array
(
array(1,11,111),
array(2,22,222),
array(3,33,333),
array(4,44,444)
);
I also Google for it but no useful PHP script found..
Result using permutation combination method
1,11,111
1,111,11
11,111
1,11,
2,11,111
2,11,1
.
.
.
.
and yes i have already tried it with permutation combination method
function permutations(array $array, $r=false)
{
switch (count($array)) {
case 1:
return $array[0];
break;
}
$keys = array_keys($array);
$a = array_shift($array);
$k = array_shift($keys); // Get the key that $a had
$b = permutations($array, 'recursing');
$return = array();
foreach ($a as $v) {
if($v)
{
foreach ($b as $v2) {
if($r == 'recursing')
$return[] = array_merge(array($v), (array) $v2);
else
$return[] = array($k => $v) + array_combine($keys, $v2);
}
}
}
return $return;
}
$x = permutations($dataArray);
echo "<pre>";
print_r($x);

How do i get unique value from an array?

$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
From the above array i need the value Dog alone. how can i get the unique value from an array?. is there any functions in php?...
Thanks
Ravi
Have a look at:
http://php.net/function.array-unique
and maybe:
http://php.net/function.array-count-values
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$counted = array_count_values($a);
$result = array();
foreach($counted as $key => $value) {
if($value === 1) {
$result[] = $key;
}
}
//$result is now an array of only the unique values of $a
print_r($result);
function getArrayItemByValue($search, $array) {
// without any validation and cheking, plain and simple
foreach($array as $key => $value) {
if($search === $value) {
return $key;
}
}
return false;
}
then try using it:
echo $a[getArrayitembyValue('Dog', $a)];
Try with:
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$aFlip = array_flip($a);
$unique = array();
foreach ( array_count_values( $a ) as $key => $count ) {
if ( $count > 1 ) continue;
// $unique[ array_search($key) ] = $key;
$unique[ $aFlip[$key] ] = $key;
}
Use following function seems to be working & handy.
<?php
$array1 = array('foo', 'bar', 'xyzzy', 'xyzzy', 'xyzzy');
$dup = array_unique(array_diff_assoc($array1, array_unique($array1)));
$result = array_diff($array1, $dup);
print_r($result);
?>
You can see its working here - http://codepad.org/Uu21y6jf
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$result = array_unique(a);
print_r($result);
try this one...

How to get values in an array this way with PHP?

From:
$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));
to:
array('A','B',..);
$output = array();
foreach ($arr as $array_piece) {
$output = array_merge($output, $array_piece);
}
return array_values($output);
On the other hand, if you want the first value from each array, what you want is...
$output = array();
foreach ($arr as $array_piece) {
$output[] = array_unshift($array_piece);
}
But I'm thinking you want the first one.
Relatively simple conversion by looping:
$newArray = array()
foreach ($arr as $a) {
foreach ($a as $key => $value) {
$newArray[] = $value;
}
}
Or, perhaps more elegantly:
function flatten($concatenation, $subArray) {
return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());
John's solution is also nice.
Something like this should work
<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));
$new_array = array();
foreach ($arr as $key => $value) {
$new_array = array_merge($new_array, array_values($value));
}
var_export($new_array);
?>
If you want all the values in each array inside your main array.
function collapse($input) {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf = array_merge($buf, collapse($i));
}
else $buf[] = $input;
return $buf;
}
Above is a modified unsplat function, which could also be used:
function unsplat($input, $delim="\t") {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf[] = unsplat($i, $delim);
}
else $buf[] = $input;
return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));

Categories