Not sure the loop I need to use every two variables - php

I have a problem where I have an array $user.
I have $_SESSION['players'] which has the total amount of $user.
I need a function where I can take the user1 and 2 and use them. Then move on to user3 and 4 and use them, and so on.. until I have used all the players. Obviously the total $user[$i] would be players-1.
Anyone have a solution for this?
Thanks

Would this suit your needs? This requires that there be an even number of players to work properly though, unless you stick in a check for odd numbers:
for ($i = 0; $i < $_SESSION['players']; $i += 2) {
$userA = $user[$i];
$userB = $user[$i + 1];
// Do things with $userA and $userB variables...
}

just because you're taught how to use for loops in one way does not mean that you're stuck continuing to use them the way you were taught:
$length = count($users);
$length = $_SESSION['players'];
for ($i = 0; $i < $length; $i += 2)
{
if (!isset($user[$i], $user[$i + 1])) break;
$userOne = $user[$i];
$userTwo = $user[$i+1];
//do stuff
}
I realized that isset wasn't necessary, the for call could be modified more:
$length = $_SESSION['players'];
for ($i = 0; ($i + 1) < $length; $i += 2)
{
$userOne = $user[$i];
$userTwo = $user[$i+1];
//do stuff
}
EDIT to change how the length was calculated:
EDIT to validate that user exists
EDIT to add consolidated version

Related

looping multidimentional array on pivot table laravel

Excuse me, I want to ask about the iteration step.
i have productdata like this
and criteria data
and alternative data as a liaison / place for the main data from the two tables above
i want to make iteration or loop $nilaiprefensi like below
with calculations like this
$nilaiprefensi[0]= [["A1,A2"],[2-4],[5-9],[10-9],[3-9],[6-8],[4-8],[120-120]]
$nilaiprefensi[1]= [["A1,A3"],[2-3],[5-8],[10-6],[3-8],[6-16],[4-9],[120-155]]
..
$nilaiprefensi[5]= [["A2,A1"],[4-2],[9-5],[9-10],[9-3],[8-6],[8-4],[120,120]]
I've tried several times to make this loop function, but it doesn't work, here's my latest code
for ($i = 0; $i <$loop; $i++) { //30
for ($j = 0; $j < count($products); $j++) {
if ($i !== $j) {
$p[$i][$j][0] = ('A' . $i + 1) . ' , A' . $j + 1;
for ($k = 1; $k < count($kriteria); $k++) {
$p[$i][$j][$k]=$alternatif[$k-1]->kriteria_data."-".$alternatif[$i]->kriteria_data;
}
}
}
}
dd($p);
What is the correct looping function to get the expected result, please help, thanks 🙏🙏

Optimisation of O(n4) complexity to O(n) in PHP nested for loop

I am writing one logic to iterate numbers first and then additional logic to putting them into particular subset of array.
What does this code do :
Code accept first $n
its create array of $n number from 1 to $n
Then started converting to subset of $main_array to possible one like
['1'] [1,2] [1,2,3] [2] [2,3] [3] etc. same like this
After creating subset i am counting those some subset which satisfy condition
Condition is xyz[0] should not come in subset with abc[0] vice versa xyz[i] should not come in subset abc[i]. Example 2 and 3 is coming subset then dont count that subset, same 1 and 4 is coming then dont count
here is my nested for loop :
$n = 1299;
$main_array = range(1,$n);
$counter = 0;
$count = sizeof($abc); // $abc and $xyz size will same always.
$abc = [2,1];
$xyz = [3,4];
for ($i=0; $i <$n; $i++) {
for($j = $i;$j < $n; $j++){
$interval_array = array();
for ($k = $i; $k <= $j; $k++){
array_push($interval_array,$main_array[$k]);
}
$counter++;
for ($l=0; $l < $count ; $l++) {
//if block here to additional condition using in_array() php function. which do $counter--
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break;
}
}
}
}
$main_array i have to create on the spot after receiving $n values.
Following is cases :
when running $n = 4 its run in 4s
when running $n = 1200 or 1299 or more than 1000 its run in 60s-123s
Expected execution timing is 9s. I reduce from 124s to 65s by removing function calling inside for loop but its not coming to point.
Expectation of code is if i have array like
$array = [1,2,3];
then
subset need to generate :
[1],[1,2],[1,2,3],[2],[2,3],[3]
Any help in this ?
It's difficult to test performance against your experience, but this solution removes one of the loops.
The way you repeatedly build $interval_array is not needed, what this code does is to just add the new value from the main array on each $j loop. This array is then reset only in the outer loop and so it just keeps the last values and adds 1 extra value each time...
for ($i=0; $i <$n; $i++) {
$interval_array = array();
for($j = $i;$j < $n; $j++){
array_push($interval_array,$main_array[$j]);
// Check output
echo implode(",", $interval_array)."\n";
$counter++;
for ($l=0; $l < $count ; $l++) {
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break 2;
}
}
}
}
adding "\n" to better understanding for subset flow.
import datetime
N = list(range(1, int(input("N:")) + 1))
affected_list = list(map(int, input("affected_list").split()))
poisoned_list = list(map(int, input("poisoned_list").split()))
start_time = datetime.datetime.now()
exclude_list = list(map(list, list(zip(affected_list, poisoned_list))))
final_list = []
for i in range(0, len(N)):
for j in range(i + 1, len(N) + 1):
if N[i:j] not in exclude_list:
final_list.append(N[i:j])
print(final_list)
end_time = datetime.datetime.now()
print("Total Time: ", (end_time - start_time).seconds)

PHP increment string value each iteration

I want to increment the int on the end of my string which together makes up the complete value.
$btnid = 'btnid1';
for($i = 1; $i < $countP; $i++) {
$btnid = 'btnid' . ++;
}
I tried different types of concatenation but I can't seem to get it to work if I just set it to 1 it works but I need the string there too.
Just append $i to the string btnid in each loop iteration.
$string = 'btnid';
for($i = 1; $i < $countP; $i++) {
$btnid = $string . $i;
}
As a side note (and seriously, DO NOT actually do this) so long as you don't go past btnid9, you can just increment the string.
$btnid = 'btnid1';
for($i = 1; $i < 9; $i++) {
$btnid++;
}
echo $btnid; // btnid9
If you go over, things get a bit weird:
$btnid++;
echo $btnid; // btnie0
Manual page: http://php.net/manual/en/language.operators.increment.php

How can I check an array for consecutive times?

I have an array of qualified times from my database:
$avail_times = array("9","11","12","13","15","16","17","18");
I want to display 4 consecutive values if they exist, if not I want to continue. For example in the above array, the only place where there are four consecutive numbers that properly follow the one before is 15,16,17,and 18
Thoughts?
This may be a duplicate problem, but I have not found a solution. My situation is a bit different. I need to show only those numbers that are consecutive four or more times. This is what I have come up with, but it is not working properly:
$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");
for($i=1, $max = count($times) + 4; $i < $max; $i++)
{
if ($avail_times[$i] == $avail_times[$i + 1] - 1)
{
echo $avail_times[$i];
}
}
This should do you:
$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");
$consec_nums = 1;
for($i = 1; $i <count($avail_times); $i++) {
if($avail_times[$i] == ($avail_times[$i - 1] + 1)) {
$consec_nums++;
if($consec_nums == 4) break;
}
else {
$consec_nums = 1;
}
}
if($consec_nums == 4) {
echo "found: {$avail_times[$i-3]}, {$avail_times[$i-2]}, {$avail_times[$i-1]}, {$avail_times[$i]}\n";
}
And a few notes:
array indexing starts at 0, when your for loop starts with $i = 1, you are skipping the first element. Notice that while I start at $i=1, I am comparing $avail_times[$i] and $avail_times[$i-1] so I do cover $avail_times[0].
I don't know what you're doing with $max = count($times). You never define $times.

how to show hit counter then make it back to zero?

i want after i've been submit form it can show hit counter..
but i want after it reach "20" it can back to zero..bcoz the limit of submit is 20 times so it can't over the limit.
how do i make it works?I've been try to this code...
<?
$limit="20";
$Query_counter=mysql_query("SELECT model FROM inspec");
$Show_counter=mysql_fetch_array($Query_counter);
$show_counter = $show_counter["model"]+1;
if($show_counter > $limit[0]) {
$show_counter = 0;
}elseif ($show_counter > $limit[1]) {
$show_counter = 0;
}
$Query_update=mysql_query("UPDATE inspec SET model=$Show_counter");
$Show_counter=number_format($Show_counter);
$Show_counter=str_replace(",",".",$Show_counter);
echo "Hit:</br><strong>$show_counter</strong>";
?>
To make a counter go up to a certain value then loop back to zero, you can use the modulus operator, which in a lot of languages (including PHP and MySQL) is %
$x = 0;
$limit = 4;
for ($i = 0; $i < 10; ++$i) {
$x = ++$x % $limit;
echo $x;
}
// 1, 2, 3, 0, 1, 2, 3, 0, 1, 2
I hope that makes enough sense. I can't really figure out from the question what exactly you want... Perhaps something like this?
UPDATE `mytable` SET `mycounter` = (`mycounter` + 1) % {{the limit}}
The concept here is to test to see if the variable you're incrementing exceeds some acceptable range as a result of the next increment. Simple increment the variable, then test its value.
In your case, just add a test after you increment the counter:
$show_counter = $show_counter["model"]+1;
if($show_counter > $limit){
$show_counter = 0;
}
Be sure to define $limit to whatever number you want to cycle on.
If you want to do this for multiple thresholds you can add additional tests. Note that you could hard-code $limit to any number or any variable you want, it's just the thing you're testing against.
<?
$Query_counter=mysql_query("SELECT model FROM inspec");
$Show_counter=mysql_fetch_array($Query_counter);
$show_counter = $show_counter["model"]+1;
$x = 0;
$limit = 20;
for ($i = 0; $i < 30; ++$i) {
$x = ++$x % $limit;
echo $x;
}
$Query_update=mysql_query("UPDATE inspec SET model= (model + 1) % 20");
$Show_counter=number_format($Show_counter);
$Show_counter=str_replace(",",".",$Show_counter);
echo "Hit:</br><strong>$show_counter</strong>";
?>

Categories