Related
Lets say I have an array of numbers: [1,2,3].
How can I loop through this array to create an array of possible permutations.
I'm expecting outputs like:
[1,2], [1,3], [2,1], [2,3], [3,1], [3,2].
Simple nested loops required for the same input array
Do the following:
$input = array(1,2,3);
$output = array();
// to get all possible permutations
// for first value in the permutation, loop over all array values
foreach ($input as $value1) {
// for second value in the permutation, loop again similarly
foreach ($input as $value2) {
if ($value1 !== $value2) // dont consider same values
$output[] = array($value1, $value2);
}
}
If i understand the question correctly, you want to have an array containing X amount of integers and get every possible combination of two distinct integers from that array?
This can be done with two for loops, one to loop through each of your array's elements, and another that combines that element with every other element.
for(int $x = 0; $x < count($arr1); $x++) {
for(int $y = 0; $y < count($arr1); $y++) {
if ($x == $y || $arr1[$x] == $arr1[$y]) {
continue;
} else {
array_push($output, [$arr1[$x], $arr1[$y]]);
}
}
}
Looking at your example I assumed you don't want repeating numbers. So I did a loop with an inner loop and compared the numbers before adding to the print Array! My first stackoverflow submissions so I'd love some feedback!
$arrayToParse = [1, 2, 3];
$arrayToPrint = [];
foreach($arrayToParse as $num1){
foreach($arrayToParse as $num2){
if($num1 != $num2){
array_push($arrayToPrint, [$num1, $num2]);
}
}
}
print_r($arrayToPrint);
// OUTPUT
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 2
[1] => 1
)
[3] => Array
(
[0] => 2
[1] => 3
)
[4] => Array
(
[0] => 3
[1] => 1
)
[5] => Array
(
[0] => 3
[1] => 2
)
)
let's say we have the following array:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 1 )
I want to reprint this array, with the [4]th key having an additional +1, like so:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 2 )
Then again:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 3 )
EDIT: The solutions given below work, however, my code does not increment the 4th key:
$filew = 'databases/stocktakemain.csv';
$getfilecont = file_get_contents($filew);
$writes = explode(",", $getfilecont);
++$writes[4];
Is there an issue with this code? Does this not apply when creating arrays through explode?
you can use the ++ to incremente in 1 your 4th array value
<?php
$array[0] = 123456;
$array[1] = 'Rothmans Blue';
$array[2] = 40;
$array[3] = 'RB44';
$array[4] = 1;
echo ++$array[4] . "<br>\n";
echo ++$array[4] . "<br>\n";
echo ++$array[4] . "<br>\n";
?>
At the end of your code, you can put
Array[4] == Array[4] + 1;
This will print out 10 arrays with that last key being an incrementing number, change the $max to make it bigger/smaller.
$max = 10;
for( $i=1; $i<=$max; $i++ ) {
print_r( array(
123456,
'Rothmans Blue',
40,
'RB44',
$i
));
}
In this case, you don't actually need to declare the key values as PHP considers the index of a value in an array to be its key.
You might try something like this if you want to print the values, then increment:
$myArray = array(123456, "Rothmans Blue", 40, "RB44", 1);
for ($i= 0; $i < 3; $i++)
{
foreach ($myArray as $key => $value)
{
print $key . " : " . $value;
if ($key == 4)
{
print "\n";
$myArray[$key] += 1; // Make sure to modify the original array, not the one you passed in as it is passed by reference.
}
}
}
If you want to increment and then print, move the print statement to the bottom of the foreach loop.
You can use end($array) function and get the last element and then add.
This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 7 months ago.
I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.
Here is my code; BUT I don't where am going wrong!
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
//$previous[value][Occurrence]
for($arr = 0; $arr < count($array); $arr++){
$current = $array[$arr];
for($n = 0; $n < count($previous); $n++){
if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
if($current != $previous[count($previous)][0]){
$previous[$n++][0] = $current;
$previous[$n++][1] = $counter++;
}
}else{
$previous[$n][1] = $counter++;
unset($previous[count($previous)-1][0]);
unset($previous[count($previous)-1][1]);
}
}
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>
array_count_values, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result:
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
if you want to try without 'array_count_values'
you can do with a smart way here
<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$count_values = array();
foreach ($input as $a) {
#$count_values[$a]++;
}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>
Simplest solution (that's where PHP rocks) - ONLY duplicates:
$r = array_filter(array_count_values($array), function($v) { return $v > 1; });
and check:
print_r($r);
Result $r:
[43] => 6
[21] => 2
[78] => 2
If you have a multi-dimensional array you can use on PHP 5.5+ this:
array_count_values(array_column($array, 'key'))
which returns e.g.
[
'keyA' => 4,
'keyB' => 2,
]
I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.
function strInArray($haystack, $needle) {
$i = 0;
foreach ($haystack as $value) {
$result = stripos($value,$needle);
if ($result !== FALSE) return TRUE;
$i++;
}
return FALSE;
}
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
for ($i = 0; $i < count($array); $i++) {
if (strInArray($array,$array[$i])) {
unset($array[$i]);
}
}
var_dump($array);
You can also use it with text items array, u will get number of duplicates properly, but PHP shows
Warning: array_count_values(): Can only count STRING and INTEGER
values!
$domains =
array (
0 => 'i1.wp.com',
1 => 'i1.wp.com',
2 => 'i2.wp.com',
3 => 'i0.wp.com',
4 => 'i2.wp.com',
5 => 'i2.wp.com',
6 => 'i0.wp.com',
7 => 'i2.wp.com',
8 => 'i0.wp.com',
9 => 'i0.wp.com' );
$tmp = array_count_values($domains);
print_r ($tmp);
array (
'i1.wp.com' => 2730,
'i2.wp.com' => 2861,
'i0.wp.com' => 2807
)
Count duplicate element of an array in PHP without using in-built
function
$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
for($i=0;$i<$arrlength-1;$i++)
{
$key=$arraychars[$i];
if($arrCount[$key]>=1)
{
$arrCount[$key]++;
} else{
$arrCount[$key]=1;
}
echo $arraychars[$i]."<br>";
}
echo "<pre>";
print_r($arrCount);
There is a magical function PHP is offering to you it called in_array().
Using parts of your code we will modify the loop as follows:
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
if (in_array($array[$arr], $arr2)) {
++$counter;
continue;
}
else{
$arr2[] = $array[$arr];
}
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>
The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.
You can do it using foreach loop. (Demo)
$array = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
$set_array[$value]++;
}
print_r($set_array);
Output:
Warning: Undefined array key 1 in /in/aGPqe on line 6
Warning: Undefined array key 2 in /in/aGPqe on line 6
Warning: Undefined array key 3 in /in/aGPqe on line 6
Warning: Undefined array key 4 in /in/aGPqe on line 6
Warning: Undefined array key 5 in /in/aGPqe on line 6
Warning: Undefined array key 6 in /in/aGPqe on line 6
Warning: Undefined array key 88 in /in/aGPqe on line 6
Array
(
[1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 2
[6] => 2
[88] => 1
)
I came here from google looking for a way to count the occurrence of duplicate items in an array. Here is the way to do it simply:
$colors = ["red", "green", "blue", "red", "yellow", "blue"];
$unique_colors = array_unique($colors); // ["red", "green", "blue", "yellow"]
$duplicates = count($colors) - count($unique_colors); // 6 - 4 = 2
if ($duplicates == 0) {
echo "There are no duplicates";
}
echo "No. of Duplicates: " . $duplicates;
// Output: No. of Duplicates are: 2
How array_unique() works?
It elements all the duplicates.
ex:
Lets say we have an array as follows -
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");
When you do $cars = array_unique($cars);
cars will have only following elements.
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");
To read more: https://www.php.net/manual/en/function.array-unique.php
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
$input = [1,2,1,3,2,4,10];
//if give string
//$input = "hello hello how are you how hello";
//$array = explode(' ',$input);
$count_val = [];
foreach($array as $val){
$count_val[$val]++;
}
print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )
I have 2 arrays in PHP. One of them holds a list of dates, the other a list of numbers.
Array1
(
[0] => 2010-06-14
[1] => 2010-06-14
[2] => 2010-06-14
[3] => 2014-01-26
[4] => 2014-01-26
)
Array2
(
[0] => 120
[1] => 100
[2] => 60
[3] => 140
[4] => 30
)
The value [0] in Array2 belongs with the date [0] in Array1. What I am trying to do is add all of the values in Array2 together, based on the date. Any dates that match should have their values added together. So for example at the end I would like something like:
$date = 2010-06-14;
$value = 280;
$date = 2014-01-26;
$value = 170;
...and so on.
I've searched though the site but was unable to find exactly what I needed. Any help would be appreciated...
You can iterate $values, and get the corresponding date from $dates to use as the key in your result array.
foreach ($values as $key => $value) {
$result[$dates[$key]] = $value + ($result[$dates[$key]] ?? 0);
}
The output will be like this:
array (size=2)
'2010-06-14' => int 280
'2014-01-26' => int 170
$sum=0; // New Element
$Array3[][]=0; // New 2D array
$p=0; // Counter for 2D array
for($i=0;$i<5;$i++) // Single loop for traversing
{
$date=Array1[$i]; // Start for a date
while($date==Array1[$i]){ // For for Similar date
$sum=$sum+Array2[$i]; // Adding values of similar date
$i++; // Increment array
}
$Array3[$p]["date"]=$date; // Array3 date element
$Array3[$p]["sum"]=$sum; // Array4 date element
$i--; // Reducing a value which is incremented in while loop
}
Array3 is like
Array3
(
[0] => array( 'date' => " ",'sum' => " ")
[1] => array( 'date' => " ",'sum' => " ")
)
Are you trying to count all of the values in Array2 that have an entry in Array1 that matches some predefined target value?
If so, this for loop version should work:
private function forLoopVersion($array1, $array2, $target) {
$result = 0;
for ($i = 0; $i < count($array1); ++$i) {
if ($array1[$i] == $target) {
$result += $array2[$i];
}
}
return $result;
}
Also, this foreach loop version might work, but I do not know if the $key for $array1 can be used to index an element in $array2. You could try it:
private function foreachLoopVersion($array1, $array2, $target) {
$result = 0;
foreach ($array1 as $key => $value) {
if ($value == $target) {
$result += $array2[$key];
}
}
return $result;
}
$newArray = array();
for($i = 0; $i < count(Array1); $i++) {
$newArray[$Array1[$i]] = $Array2[$i];
}
echo $newArray[$date1] + $newArray[$date2];
Put the dates as keys to for easy math.
This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 7 months ago.
I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.
Here is my code; BUT I don't where am going wrong!
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
//$previous[value][Occurrence]
for($arr = 0; $arr < count($array); $arr++){
$current = $array[$arr];
for($n = 0; $n < count($previous); $n++){
if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
if($current != $previous[count($previous)][0]){
$previous[$n++][0] = $current;
$previous[$n++][1] = $counter++;
}
}else{
$previous[$n][1] = $counter++;
unset($previous[count($previous)-1][0]);
unset($previous[count($previous)-1][1]);
}
}
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>
array_count_values, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result:
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
if you want to try without 'array_count_values'
you can do with a smart way here
<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$count_values = array();
foreach ($input as $a) {
#$count_values[$a]++;
}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>
Simplest solution (that's where PHP rocks) - ONLY duplicates:
$r = array_filter(array_count_values($array), function($v) { return $v > 1; });
and check:
print_r($r);
Result $r:
[43] => 6
[21] => 2
[78] => 2
If you have a multi-dimensional array you can use on PHP 5.5+ this:
array_count_values(array_column($array, 'key'))
which returns e.g.
[
'keyA' => 4,
'keyB' => 2,
]
I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.
function strInArray($haystack, $needle) {
$i = 0;
foreach ($haystack as $value) {
$result = stripos($value,$needle);
if ($result !== FALSE) return TRUE;
$i++;
}
return FALSE;
}
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
for ($i = 0; $i < count($array); $i++) {
if (strInArray($array,$array[$i])) {
unset($array[$i]);
}
}
var_dump($array);
You can also use it with text items array, u will get number of duplicates properly, but PHP shows
Warning: array_count_values(): Can only count STRING and INTEGER
values!
$domains =
array (
0 => 'i1.wp.com',
1 => 'i1.wp.com',
2 => 'i2.wp.com',
3 => 'i0.wp.com',
4 => 'i2.wp.com',
5 => 'i2.wp.com',
6 => 'i0.wp.com',
7 => 'i2.wp.com',
8 => 'i0.wp.com',
9 => 'i0.wp.com' );
$tmp = array_count_values($domains);
print_r ($tmp);
array (
'i1.wp.com' => 2730,
'i2.wp.com' => 2861,
'i0.wp.com' => 2807
)
Count duplicate element of an array in PHP without using in-built
function
$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
for($i=0;$i<$arrlength-1;$i++)
{
$key=$arraychars[$i];
if($arrCount[$key]>=1)
{
$arrCount[$key]++;
} else{
$arrCount[$key]=1;
}
echo $arraychars[$i]."<br>";
}
echo "<pre>";
print_r($arrCount);
There is a magical function PHP is offering to you it called in_array().
Using parts of your code we will modify the loop as follows:
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
if (in_array($array[$arr], $arr2)) {
++$counter;
continue;
}
else{
$arr2[] = $array[$arr];
}
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>
The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.
You can do it using foreach loop. (Demo)
$array = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
$set_array[$value]++;
}
print_r($set_array);
Output:
Warning: Undefined array key 1 in /in/aGPqe on line 6
Warning: Undefined array key 2 in /in/aGPqe on line 6
Warning: Undefined array key 3 in /in/aGPqe on line 6
Warning: Undefined array key 4 in /in/aGPqe on line 6
Warning: Undefined array key 5 in /in/aGPqe on line 6
Warning: Undefined array key 6 in /in/aGPqe on line 6
Warning: Undefined array key 88 in /in/aGPqe on line 6
Array
(
[1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 2
[6] => 2
[88] => 1
)
I came here from google looking for a way to count the occurrence of duplicate items in an array. Here is the way to do it simply:
$colors = ["red", "green", "blue", "red", "yellow", "blue"];
$unique_colors = array_unique($colors); // ["red", "green", "blue", "yellow"]
$duplicates = count($colors) - count($unique_colors); // 6 - 4 = 2
if ($duplicates == 0) {
echo "There are no duplicates";
}
echo "No. of Duplicates: " . $duplicates;
// Output: No. of Duplicates are: 2
How array_unique() works?
It elements all the duplicates.
ex:
Lets say we have an array as follows -
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");
When you do $cars = array_unique($cars);
cars will have only following elements.
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");
To read more: https://www.php.net/manual/en/function.array-unique.php
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
$input = [1,2,1,3,2,4,10];
//if give string
//$input = "hello hello how are you how hello";
//$array = explode(' ',$input);
$count_val = [];
foreach($array as $val){
$count_val[$val]++;
}
print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )