Check how many variables equal zero with php - php

I have numerous variables and I need to print a numeric value for how many of these variables are equal to zero:
$var1 = '2';
$var2 = '0';
$var3 = '4';
//check how many variables = 0
$zeros = ?
//should be a numeric value this example should print '1'
echo $zeros
Thanks for any suggestions!

This gets a list of all defined variables, and counts how many are === 0 and excludes the $_GET, $_POST, and $_COOKIE globals.
If you define this code in a function, then only the variables in that scope are counted.
<?php
$value = 0;
$var = 1;
$test = false;
$nine = 0;
$zero = 9;
$zeroes = 1; // set to 1 so we don't count this
$vars = get_defined_vars();
foreach($vars as $var) {
if (is_array($var) && (
isset($var['_GET']) || isset($var['_POST']) ||
isset($var['_COOKIE']))
) {
continue; // don't count superglobal arrays
}
if ($var === 0) $zeroes++;
}
$zeroes -= 1; // subtract the initial value
echo "There are $zeroes zero values."; // There are 2 zero values.
EDIT: It could be modified to be a function that would work recursively if you needed to check the values of arrays for example. You could call it from the global scope like this:
$zeroes = countZero(get_defined_vars());
And then the function could detect arrays and call itself until it has searched all vars.

if($var1 == 0) $zeros++; repeat for var2, 3, etc.
Use variable variables to generate variables from a string if they all follow the varX pattern where X is a number.
$var1 = '2';
$var2 = '0';
$var3 = '4';
$zeros = 0;
for($i = 1; $i <= 3; $i++) {
$var = ${'var' . $i};
if($var == 0) $zeros ++;
}
echo $zeros;

I do not understand the purpose of what you are trying to achieve here and maybe I am misunderstanding the need but the following yet simple code does it:
$var1 = '2';
$var2 = '0';
$var3 = '4';
$zeros = ($var1 =='0')?1:0 + ($var2 =='0')?1:0 + ($var3 =='0')?1:0;
echo $zeros
Basically I nested ternaly conditional expressions instead of using regular if then elses.

I put all of my variables into an array, looped with foreach and added to the $zeros variable:
$values = array('0' => $var1, '1' => $var2, '2' => $var3);
$zeros = 0;
foreach($values as $v) {
if($v === '0')
$zeros++;
}
echo $zeros;
I found this was an easy solution, thanks for the input though!

Related

PHP if statement and ob_flush

If they are same do nothing, if they are different do the bottom and make them same. Whole script is in a loop but the loop is only doing else. Like it is not checking for conditions. What am I doing wrong?
for ($int = 0; $int < 10, $int+1){
$array = $getarray();
foreach ($array as $array){
$var1 = $array->id;
$var2 = null;
if ($var1 == $var2){
echo ('skip');
}else{
echo '<br>'.$var1.'<br>';
ob_flush();
$var2 = $var1;
}
}
}
Initially var2 is null and var1 gets string value. So it performs else and var2 gets the var1 string.
Next Loop if var1 has not changed, it will equal var2. So it does nothing and skips
I don't understand the logic of these loops but this is how you should do it:
for ($int = 0; $int < 10, $int++) {
/*
* I suppose getarray() is a function.
* If you have a variable $getarray containing the name of another function
* then you should change getarray() to $getarray()
*/
foreach (getarray() as $array) {
if (is_null($array->id)) {
echo ('skip');
} else {
echo "<br />{$array->id}<br />";
ob_flush();
}
}
}
Your code does not work properly, as how many times your loop will execute, your $var2 will become null, so not a single time you will be reached at the point where your $var1 & $var2 values are same.
So instead please try the following code.
for ($int = 0; $int = 10; $int+1){
$array = $getarray();
$var2 = null;
foreach ($array as $array){
$var1 = $array->id;
if ($var1 == var2){
echo ('skip');
}else{
echo '<br>'.$var1.'<br>';
ob_flush();
$var2 = $var1;
}
}
}

Get key after inserting into array PHP

I'm looking for something like this:
$a = array();
$var1 = 'var1';
$var2 = 'var2';
$i = array_push($a, $var1);
$j = array_push($a, $var2);
echo $i;
echo $j;
The expected output would be:
0
1
I want to know the index of the object I just inserted, to be able to find it quickly afterwards. I think array_push gives me the size of the resulting array, not the index for the recently inserted element
array_push return new number of elements in the array, so decrement the return value by 1
Try this:
$a = array();
$var1 = 'var1';
$var2 = 'var2';
$i = array_push($a, $var1) - 1;
$j = array_push($a, $var2) - 1;
echo $i;
echo $j;
function my_push_array(&$array, $value){
$array[] = $value;
end($array);
return key($array);
}
$a = ['h','e','l','l'];
echo my_push_array($a, 'o'); //returns 4

php - use variable variable in while loop

I'm a bit confused about variable variables.
What I like to do is print the value of $var1, $var2 and $var3:
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
echo $var.$i;
$i++;
}
I know $var.$i; is not correct, but I think it shows what I would like to achieve; the while-loop should change it to $var1, $var2 and $var3;
I've tried the following:
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
$current_var = 'var'.$i;
$current_var = $$current_var;
echo $current_var;
$i++;
}
But that doesn't work. I think because $var1, $var2 and $var3 are recreated in the while-loop instead of using the actual value. Not sure if that's correct, but that the only thing I can think of.
Try this instead:
echo ${"var".$i};
Curly braces can resolve to variable names without having to use the dollar-dollar approach.
See: Variable Variables in PHP
Try this one.
<?php
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';
$i = 1;
while ( $i <=3 ) {
echo ${'var'.$i};
$i++;
}
?>
Are you trying to do something like this. Then use array
$my_data = array();
$my_data[1] = 'a';
$my_data[2] = 'b';
$my_data[3] = 'c';
// Method 1
$i = 1;
while ($i <= 3) {
echo $my_data[$i];
$i++;
}
// Method 2
foreach ($my_data as $data) {
echo $data;
}
// Output
abc
abc

Simple PHP Question: Using an IF statement inside a FOR loop

Inside a for loop, I'm trying to set a variable based on the what iteration of the loop it's on:
<?php
for ($k = 0; $k < 3; $k++){
if ($k = 0) : $var = 'zero';
elseif ($k = 1) : $var = 'one';
else : $var = 'two';
endif;
?>
This is iteration <?php echo $var; ?>.
<?php }; ?>
But it continues looping forever until my browser freezes... what's going on? Any help would be greatly appreciated!
You are essentially setting $k to be 0 and 1. Comparing values use '=='.
Try this instead.
<?php
for($k = 0; $k < 3; $k++){
if ($k == 0)
$var = 'zero';
elseif ($k == 1)
$var = 'one';
else
$var = 'two';
?>
This is iteration <?php echo $var; ?>.
<?php } ?>
if ($k = 0)
You're setting $k to 0 here. Use == to compare values, or === to compare values and their types.
In the if statements, you are using the = operator which assigns...
then $k will always be 0 and the loop will never end.
Replace = to == in the if statements. So it will compare instead of assign $k a value.
A clearer example.-
if ($k = 1) // It will return 1, because you are assigning $k, 1.
But in
if ($k == 1) // It will return a boolean **true** if $k equals 1, **false** otherwise.
for ($k = 0; $k < 3; $k++){
if($k == 0){
$var = 'zero';
}elseif($k == 1){
$var = 'one';
}else{
$var = 'two';
}
}
echo $var;

How to identify a PHP variable is an array or not

How to check whether the PHP variable is an array?
$value is my PHP variable and how to check whether it is an array?
echo is_array($variable);
http://us3.php.net/is_array
php has function named is_array($var) which returns bool to indicate whether parameter is array or not
http://ir.php.net/is_array
is_array — Finds whether a variable is an array
http://uk.php.net/is_array
I'm adding a late answer here as I think I've got a better solution if people are using multiple array checks.
If you're simply checking a single array, then using PHP's is_array() does the job just fine.
if (is_array($users)) {
is an array
} else {
is not an array
}
However, if you're checking multiple arrays - in a loop for example - then there is a much better performing solution for this, using a cast:
if ( (array) $users !== $users ) {
// is not an array
} else {
// is an array
}
THE PROOF
If you run this performance test, you will see quite a performance difference:
<?php
$count = 1000000;
$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;
$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
echo 'error';
break;
}
}
$end_time = microtime(true);
echo 'is_array : '.($end_time - $start_time)."\n";
$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
echo 'error';
break;
}
}
$end_time = microtime(true);
echo 'cast, === : '.($end_time - $start_time)."\n";
echo "\nTested $count iterations."
?>
THE RESULT
is_array : 7.9920151233673
cast, === : 1.8978719711304

Categories