Help with For Loop. Values repeating - php

$teams = array(1, 2, 3, 4, 5, 6, 7, 8);
$game1 = array(2, 4, 6, 8);
$game2 = array();
if teams[x] is not in game1 then insert into game2
for($i = 0; $i < count($teams); $i++){
for($j = 0; $j < count($game1); $j++){
if($teams[$i] == $game1[$j]){
break;
} else {
array_push($game2, $teams[$i]);
}
}
}
for ($i = 0; $i < count($game2); $i++) {
echo $game2[$i];
echo ", ";
}
Im expecting the result to be:
1, 3, 5, 7,
However, im getting:
1, 1, 1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
How can i improve this? Thanks

Others have already answered on how to use array_diff.
Reason why your existing loop does not work:
if($teams[$i] == $game1[$j]){
// this is correct, if item is found..you don't add.
break;
} else {
// this is incorrect!! we cannot say at this point that its not present.
// even if it's not present you need to add it just once. But now you are
// adding once for every test.
array_push($game2, $teams[$i]);
}
You can use a flag to fix your existing code as:
for($i = 0; $i < count($teams); $i++){
$found = false; // assume its not present.
for($j = 0; $j < count($game1); $j++){
if($teams[$i] == $game1[$j]){
$found = true; // if present, set the flag and break.
break;
}
}
if(!$found) { // if flag is not set...add.
array_push($game2, $teams[$i]);
}
}

Your loop doesn't work because every time the element from $teams is not equal to the element from $game1, it adds the $teams element to $game2. That means each element is being added to $game2 multiple times.
Use array_diff instead:
// Find elements from 'teams' that are not present in 'game1'
$game2 = array_diff($teams, $game1);

You can use PHP's array_diff():
$teams = array(1, 2, 3, 4, 5, 6, 7, 8);
$game1 = array(2, 4, 6, 8);
$game2 = array_diff($teams,$game1);
// $game2:
Array
(
[0] => 1
[2] => 3
[4] => 5
[6] => 7
)

Related

Loop through array of values and sort

I would like you to help me with an algorithm in PHP that can loop through an array of values, sort them and print non-duplicates.
Here is the code I wrote. I want to do it with only loop and if else statement. I would appreciate any help in achieving this. Thanks
$input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];`
$count_array = count($input_array); // count the array`enter code here`
for($i = 0; $i < $count_array; $i++){ //loop through the array 1st time
$check_array = false;
//sort array
for($j = $i+1; $j < $count_array; $j++){
if($input_array[$i] > $input_array[$j]){
$non_duplicates = $input_array[$i];
$input_array[$i] = $input_array[$j];
$input_array[$j] = $non_duplicates;
}
else if($input_array[$i] == $input_array[$j] &&( $i != $j)){
$check_array = true;
break;
}
else{
$input_array[$i] != $input_array[$j];
}
}
if(!$check_array){
echo($input_array[$i]. ', ');
}
}
You can do it with 2 for cycles where the first cycle is for the first element and the 2nd cycle is always in the next position, this will help to always check if the first number is less than the second. You create a temporary variable where you store the value of the first number and you pass the value of the second number to the variable of the first one, later the temporary one that you had stored you pass it to the variable of the second number (with this you got to invert the values of one to the other).
As this is ordering them, later an if is made where it is verified if they are equal, in case of being equal a unset() is made to eliminate that data of the array.
// Array of values
$input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];
// count the length of array
$count = count($input_array);
// order array and remove duplicates
for ($i = 0; $i < $count; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
// order array
if ($input_array[$i] < $input_array[$j]) {
$temp = $input_array[$i];
$input_array[$i] = $input_array[$j];
$input_array[$j] = $temp;
}
// delete duplicates
if ($input_array[$i] == $input_array[$j]) {
unset($input_array[$j]);
}
}
}
// Return an array with elements in reverse order
$input_array = array_reverse($input_array);
You get something like this:
Dump => array(9) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(7)
[5] => int(5)
[6] => int(8)
[7] => int(9)
[8] => int(12)
}

PHP: different elements between two arrays

I have two different arrays like this
$array1 = [1, 2, 8, 10];
$array2 = [2, 4, 6, 8, 10, 15, 1];
I want to get the common elements and uncommon elements between them.
I almost figured out how to get the common ones as the code below but I can't get uncommon elements.
for($x = 0; $x < count($array1); $x++) {
for($z = 0; $z < count($array2); $z++) {
if ( $array1[$x] == $array2[$z] ) {
$array3 = $array1[$x];
print_r($array3);
} elseif ($array1[$x] !== $array2[$z]) {
// code...
}
}
}
How to get those uncommon or different elements between the two arrays without using a built-in PHP method then output them in a new array.
You can get the uncommon elements by using in_array() function
<?php
$array1 = [1, 2, 8, 10];
$array2 = [2, 4, 6, 8, 10, 15, 1];
$result = [];
for($i = 0;$i < sizeof($array2);$i++){
if(!in_array($array2[$i],$array1)){
$result[] = $array2[$i];
}
}
?>
Output
Array
(
[0] => 4
[1] => 6
[2] => 15
)

Given two arrays combine common values

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];
The indexes of $names and $money correspond to each other.
I need to find the most efficient way to add common $money to each $names and print only the even values.
For example, john appears two times, with 2 and 3 money. So johnhas 5 money.
Desired output:
mark: 20
brian: 8
paul: 6
I am thinking of looping through each array, but this is O(n^2) Is there an easier way?
Make associative array (hash) for result:
$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];
$result = [];
for ($i = 0; $i < count($names); $i++) {
if (!isset($result[$names[$i]])) {
$result[$names[$i]] = 0;
}
$result[$names[$i]] += $money[$i];
}
arsort($result); // reverse (big first) sort by money
print_r($result);
just loop through names and use it keys for money array:
$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];
$res = [];
foreach ($names as $key => $value) {
$res[$value] = isset($res[$value]) ? $res[$value] + $money[$key] : $money[$key];
}
var_dump($res);
You just have to loop through $names once and set name as key in a result- variable.
$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];
$data = [];
foreach ($names as $key => $name) {
if (!isset($data[$name])) {
$data[$name] = 0;
}
$data[$name] += $money[$key];
}
print_r($data);
Maybe you'll need a check, if both arrays have the same size.
$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];
$result = [];
foreach ($names as $index => $name) {
if (empty($result[$name]) {
$result[$name] = $money[$index];
} else {
$result[$name] += $money[$index];
}
}
print_r($result);

PHP Array: Calculate difference among values in same array

I am trying to compute the difference between all values in an array and store them (the differences) in a single array.
An ideal example would be something like this:
<?php
$data = array('1', '5', '12');
// Compute the difference between each value with another value.
?>
And then I like to have the following results in an array:
4, 11, 7
How can I achieve it?
try this
$data = array('1', '5', '12');
$differences=[];
for($i=0;$i<count($data);$i++){
for($j=$i+1;$j<count($data);$j++){
$differences[]=abs($data[$i]-$data[$j]);
}
}
print_r($differences);
results in
Array
(
[0] => 4
[1] => 11
[2] => 7
)
Try by having double for loops one for iterating current array and another to start comparing and store it in result array.
I am not very sure about your output as information is less but you can try as follow:
var a= ["1","5","12"]
for(i=0;i<3;i++){for(j=0;j<3;j++){if(i>j)console.log(a[i]-a[j])}}
Check this https://3v4l.org/9oiqs
$data = [1, 5, 12, 15, 20, 25,];
function getDifferences($aValues)
{
$aDiff = [];
$iSize = count($aValues);
for ($i = 0; $i < $iSize; $i++)
{
for ($j = $i + 1; $j < $iSize; $j++)
{
$aDiff[$aValues[$i]][] = abs($aValues[$i] - $aValues[$j]);
}
}
return $aDiff;
}
function printDifferences($aValues){
foreach ($aValues as $iNumber => $aDiffs){
echo "Differences for $iNumber: " . implode(', ', $aDiffs) . PHP_EOL;
}
}
$aDiff = getDifferences($data);
printDifferences($aDiff);
Result
Differences for 1: 4, 11, 14, 19, 24
Differences for 5: 7, 10, 15, 20
Differences for 12: 3, 8, 13
Differences for 15: 5, 10
Differences for 20: 5

How to add multidimensional array values in a loop

I have 52 weeks array's and each week array has a sub array with 9 values.
now I need to add a value 0 at the begin of each array and every next week I need 1 value more.
For example (notice that the 0-8 will be in a for loop)
$vruchtzettings_week["week1"][0-8] = 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week2"][0-8] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week3"][0-8] = 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week4"][0-8] = 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Though I can't really test it, I believe this would do it for you. What you're doing is really convoluted.
$week = 1;
while ($week <= 52) {
$sum = 0;
for ($sub = 0; $sub < 9; $sub++, $week++;) {
$totaal_vruchtzetting_week[$week] = $totaal["week$week"][$sub] + $sum;
$sum += $totaal["week$week"][$sub];
}
}
Like I said, you will probably have to tweek this a little. But it will get you started.

Categories