Loop in an array
#1

So uh I was trying to check every content of the array if each of them are equal to one, but I'm kinda having troubles in how to shorten it. Here's how far I've gone

PHP код:
if((PlayerInfo[id][Inv][1] == 1) || (PlayerInfo[id][Inv][2] == 1) || (PlayerInfo[id][Inv][3] == 1) || (PlayerInfo[id][Inv][4] == 1) || (PlayerInfo[id][Inv][5] == 1) || (PlayerInfo[id][Inv][6] == 1) || (PlayerInfo[id][Inv][7] == 1) || (PlayerInfo[id][Inv][8] == 1) || (PlayerInfo[id][Inv][9] == 1)) 
Reply
#2

You need a loop with iteration variable going from 1 to 9. Why do you start from 1 when array index start from 0 is another question.

To learn more about loops: https://sampwiki.blast.hk/wiki/Control_Structures#Loops
Reply
#3

Right, that was my fault, should've been 0.

How do I check the content of every array if their value is equal to 1?
Reply
#4

You can use a for loop, to loop from 0 to size - 1 (where size the size of the array, since indexes start at zero the last index will be size - 1).

Similar to a for-loop looping through all players, but here MAX_PLAYERS would be the size of the array (the rest is the same, if you know what I mean). If you use i as variable for the loop, you can use i for the index of the array.

To check if all the indexes have the same value, you can declare a variable (bool for clarity) before the array and set it to true or 1.

While looping through the array, you can check if the current index has the value you want. If it doesn't set the aforementioned variable to false or 0.

After the loop finished, you can then know if any value is different if the variable is true or false.
Reply
#5

So uh, something like this?

PHP код:
for(new i=0i<10i++)
{
    if(
PlayerInfo[id][Inv][i] == 1)
    {
        
//code
    
}

Would this code check if the content of every [Inv] variable is equal to 1?
Reply
#6

Quote:
Originally Posted by NealPeteros
Посмотреть сообщение
So uh, something like this?

PHP код:
for(new i=0i<10i++)
{
    if(
PlayerInfo[id][Inv][i] == 1)
    {
        
//code
    
}

Would this code check if the content of every [Inv] variable is equal to 1?
Not exactly, this will execute your code for every slot that is 1.

Create a variable before the loop to keep track if all of them are 1:

Код:
new bool:all_true = true;

for(new i=0; i<10; i++)
{
	if(PlayerInfo[id][Inv][i] != 1) // One of them is not 1, so set the variable to false
	{
		all_true = false;
		break; // Since we know that at least one is not true, we don't need to continue checking... Stop the loop
	}
}

if(all_true) // All indexes are 1
{
	// Code
}
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)