Reputation: 532
I have rows in my teams
table named player1
, player2
, player3
... player12
. In PHP script i set them as variables ($player1
,$player2
...) and want to loop through them to check if they are NULL
, and if they are not to count them.
How may I increment a variable in PHP? I have tried doing it likes this:
<?
$playerspicked = 0;
for($i = 1; $i <= 12; $i++) {
$playercheck = "$player"+$i;
if($playercheck != 0) {
$playerspicked++;
}
}
?>
but this wouldn't work.
Upvotes: 1
Views: 331
Reputation: 56
In your case there is a much easier way to count all the not null players in the team.
echo count(array_filter($yourTeam));
the array_filter function without a second parameter will automatically remove the null entries.
Upvotes: 1
Reputation: 8621
You can do this with complex expressions (curly brackets {}
) around a variable name.
if(empty(${"player$i"})) {
//player$i is empty
}
complex expressions allow you to set variable names dynamically.
To help you better understand how these work, I will show you that you can also use these just like regular string concatenation like so
$variable = "many test";
echo "this is a test echo. {$variable}";
I commonly use this for generating a variable for many array variables based on their key
$array = array("key1" => "value1", "key2" => "value2");
foreach($array as $key => $value) {
${$key} = $value;
}
The code above would create 2 variables, $key1
and $key2
, with the appropriate value associated with them.
Alternatively, I'm pretty sure you can just add another $
to the front of your variable, but I would say this is harder to read and figure out what's going on.
$playercheck = "player"+$i;
if($$playercheck != 0) {
$playerspicked++;
}
Upvotes: 3