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;
Related
This question already has answers here:
How to find first array element with value greater than X in PHP?
(2 answers)
Closed 1 year ago.
Say, there is an array and a number:
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
How can I find an index of the array element the value of which is less than the number?
In the above example it will be the 'b' index of which is 1.
You could sort the array by the values then loop through it until a number is hit above the $num. Here is a quick example:
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
$sortedValues = $values;
asort($sortedValues);
while (($current = current($sortedValues)) !== false && $current < $num) {
$lastValue = key($sortedValues);
next($sortedValues);
}
echo $lastValue;
I got it:
$values = ['a'=>1, 'b'=>20, 'c'=>30, 'd'=>40, 'e'=>50];
$num = 55;
$i = null;
foreach ($values as $k => $v){
if ($v == $num){
echo $v;
break;
}
elseif ($num >= 1 && $v > $num){
echo $values[$i];
break;
}
elseif ($num > end($values)){
echo end($values);
break;
}
$i = $k;
}
May be array_filter can be some more handy:
$values = ['a'=>1, 'b'=>20, 'c'=>30, 'd'=>40, 'e'=>50];
$num = 45;
// filter items less than $num
$lesser = array_filter($values, function($v) use($num) {
return $v < $num;
});
// get necessary item/index from filtered, last for example
$lesserKeys = array_keys($lesser);
$lastOfLessKey = end($lesserKeys);
$lastOfLess = end($lesser);
var_dump($lastOfLessKey, $lastOfLess); // d 40
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
foreach($value as $key => $val){
if( (int) $val == (int) $num){
echo 'this is what you are searching. key is: '.$key.', value is: '.$val;
}
}
I want to remove empty variable from array. I have explored different methods but couldn't be able to do this correctly. I have tried in the following ways:
$field1 = 6;
$field2 = 15;
$field3 = 7;
$demo = array($field1=>"info1", $field2=>"info2",$field3=>"field3");
echo "$demo[$field3]";
If any of the variables ($field1, $field2 or field3) is zero the result should be Null.
try this
$field1 = 6;
$field2 = 15;
$field3 = 7;
$demo = array($field1=>"info1", $field2=>"info2",$field3=>"field3");
$demo = isset($demo[0]) ? null : $demo;
echo "$demo[$field3]";
<?php
foreach($array as $key => $value){
if($key == false || $key == 0){
unset($array[$key]);
}
}
?>
Do you mean that?
With that, echo "$demo[$field3]"; will output NULL if $field3 == 0.
please try this way;
for($i = 0; $i<count($demo); $i++){
if($demo[$i) == 0)$demo[$i]=NULL
}
In this code if the key of array is Null or 0. Item Delete from array.
<?php
foreach($array as $key => $value){
if($key == false || $key == 0){
unset($array[$key]);
}
}
?>
You should try this :
$field1 = 6;
$field2 = 15;
$field3 = 7;
$demo = array($field1=>"info1", $field2=>"info2",$field3=>"field3");
foreach($demo as $key=>$val){
//echo $key."----------".$val; just to check
if($key == '0'){
$val='Null';
}
}
I'm trying to write an algorithm to find the GCD ( Greatest common divisor ) but the result of my function is Array what I'm doing wrong !! please I don't want another aproche or a ready algorithme copie past I wanna know what i'm doing wrong
<?php
function pgcd($val1, $val2){
if (!is_numeric($val1) || !is_numeric($val2)){
return null;
}
$i = 1;
$final = array();
while($i <= min($val1, $val2)){
if ($i % $val1 === 0 && $i % $val2 === 0){
$final[] = $i;
}
$i++;
}
return $final;
}
echo pgcd(120,420);
?>
First of all: you want to find gcd or all common divisors?
If gcd, then you have some errors in your code:
1) replace either $final = array(); with $final = null;, or return $final; with return $final[0];;
2) replace if ($i % $val1 === 0 && $i % $val2 === 0) with if ($val1 % $i === 0 && $val2 % $i === 0);
3) replace $final[] = $i; with $final = $i;
OR:
1) replace if ($i % $val1 === 0 && $i % $val2 === 0) with if ($val1 % $i === 0 && $val2 % $i === 0);
2) replace return $final; with return max($final);;
Returned $final is an array. For print array use print_r(YOUR_VALUE). if u using 'echo' u can print only string value, not array;
it says an error undefined offset i dont know what causes it
im trying to shuffle $numberarray without repeating the number
heres the code
$numberarray = array(1,2,3,4,5,6,7,8,9,10);
for($counter=0;$counter<=9;$counter++)
{
$b = $counter - 1;
$a = $numberarray[$counter];
$numberarray[$counter] = rand(1,10);
do
{
$numberarray[$counter] = rand(1,10);
while($b != 0)
{
if($numberarray[$counter] == $numberarray[$b])
{
$numberarray[$counter] = rand(1,10);
$b = $counter - 1;
//echo $b;
}
else
{
$b--;
}
}
}while($a == $numberarray[$counter]);
echo $numberarray[$counter].", ";
}
sample output $numberarray = {3,4,5,1,2,7,9,10,8,5}
This would be better:
(By the way you don't need an extra condition before the while since while act like a condition itself)
$numberarray = array(1,2,3,4,5,6,7,8,9,10);
for($counter=0;$counter<=9;$counter++)
{
$b = $counter - 1;
$a = $numberarray[$counter];
$numberarray[$counter] = rand(1,10);
do
{
$numberarray[$counter] = rand(1,10);
while($b >0)
{
if($numberarray[$counter] == $numberarray[$b])
{
$numberarray[$counter] = rand(1,10);
$b = $counter - 1;
//echo $b;
}
else
{
$b--;
}
}
}while($a == $numberarray[$counter]);
echo $numberarray[$counter].", ";
}
Even if there is no more error, your code repeat numbers sometimes, so I would symply do it like this using shuffle:
$numberarray2 = array(1,2,3,4,5,6,7,8,9,10);
shuffle($numberarray2);
print_r($numberarray2);
The problem is that in the first $b is equal to -1 that's why you get the error so i think you should delete the if condition and edit the while statement to while($b!=-1).
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!