How to check if a array is even or odd php - php

I have an array and I need to find if the values are even or odd and print them.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
And I print the results in array format (I`m looking to use "echo" to print each)
I found a solution that is to create a while loop and use modules %2
like:
$foreach ($numbers % 2==0) { //even
echo "value is even";
} else {
echo "value is odd";
}
But it doesnt work, and i only have experience working with numbers in if statements and loops. How would i go about this when working with an array.
Thanks in advance.

Welcome to Stackoverflow.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach ($numbers as $n) {
echo 'value '. $n .' is: ';
echo ($n % 2 == 0) ? 'even' : 'odd';
echo "\n"; // optional
}

You can try also like this, this is more understandable for you
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach($numbers as $value)
{
if($value%2==0)
{
echo $value 'is even <br/>';
}
else
{
echo $value 'is odd <br/>';
}
}

Here is the code,
You are in right direction but there will be a little bit of change in your code i.e. you are applying condition on whole array which is wrong you have to fetch single value and apply even number condition.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach($numbers as $var)
{
if($var%2==0)
{
echo $var;
}
else
{
echo $var;
}
}

Related

PHP. Counting number of strings satisfying an specific condition in a foreach loop

I'm trying to find the number of strings that satisfy some conditions in a foreach loop. This is what I've tried so far:
<?php
$list = $item->getProperty();
$n = 0;
foreach($list as $single) {
$designation = $single->getPropertyName(); // var_dump($designation); outputs 150 strings
if (strpos($designation, 'foo') === 0) { // var_dump($designation); outputs 5 strings containing 'foo' in their designation names
$n++;
echo count($n);
}
}
?>
echo count($n); returns 11111 instead of returning 5 which is the value I want to obtain.
Could someone help me out a bit?
<?php
$list = $item->getProperty();
$n = 0;
foreach($list as $single) {
$designation = $single->getPropertyName(); // var_dump($designation); outputs 150 strings
if (strpos($designation, 'foo') === 0) { // var_dump($designation); outputs 5 strings containing 'foo' in their designation names
$n++;
}
}
echo $n;
If you would like to achieve the same in a more functional and elegant way, you could use array_reduce
array_reduce($item->getProperty(), function($sum, $single) {
if (strpos($single->getPropertyName(), 'foo') === 0) {
$sum++;
}
return $sum;
});
A less readable, but more elegant one-line solution would look like:
array_reduce($item->getProperty(), function($sum, $single) { return (strpos($single->getPropertyName(), 'foo') === 0) ? ++$sum : $sum; }
And now that we have short arrow functions in PHP, you can use this if you are running on PHP 7.4:
array_reduce($item->getProperty(),
fn($sum, $single) => (strpos($single->getPropertyName(), 'foo') === 0) ? ++$sum : $sum);

Foreach different with first array in php

This is what I tried
$a = array("a", "b", "c");
$b = $a[0];
if (array_search($b,$a) == 0) {
echo $a[0]." and some code";
}
else {
foreach($a as $c) {
echo $c."and some different code";
}
}
And I want the outcome to be
a and some code
b and some different code
c and some different code etc...
Your logic of finding the first item seems a bit redundant, also as the foreach() is only done if it doesn't find the first item (which it always will).
To simplify the code, just echo out the first item, use array_shift() to remove this value and foreach() over the rest of the array...
$a=array("a","b","c");
echo $a[0]." and some code".PHP_EOL;
array_shift($a);
foreach($a as $c){
echo $c." and some different code".PHP_EOL;
}
You need to move foreach one level up and you do not need to search if you explicitly specify value. Plus some other minor fixes. This is the solution closest to your code:
$a = array("a","b","c");
$b = $a[0];
foreach($a as $c) {
if ($b == $c) {
echo $b . " and some code\n";
} else {
echo $c . " and some different code\n";
}
}
You could use a foreach with the index defined and use a case / if statements?
foreach ($arr as $key => $value) {
if($key==0){
echo $value . "and some code";
} else if ($key===1){
echo $value . "and some different code";
} else {
echo $value . "and some even more different code";
};
};

Convert 'if else' statements to a loop in PHP?

How can I convert this into a loop in PHP?
$number = 4; // This number is unknown and can be any number.
if ($number === 1) {
echo $red;
} else if ($number === 2) {
echo $yellow;
} else if ($number === 3) {
echo $orange;
} else if ($number === 4) {
echo $black;
} else if ($number === 5) {
echo $green;
} else if ($number === 6) {
echo $grey;
} else if ($number === 7) {
echo $brown;
} else if ($number === 8) {
echo $blue;
} else if ($number === 9) {
echo $silver;
} else if ($number === 10) {
echo $gold;
} else if ($number === 11) {
echo $white;
}
etc...
Right now the $number can be any number, so I would have to somehow loop through the numbers from 1 to unlimited, until it finds what $number is equal to. In this case, number is equal to 4.
I'm not sure why you want to do it like this, but:
$i = 1;
while ($i !== $number) {
$i++;
}
$int = $i;
To do what you want, you should use an array map, but an switch might do the trick too.
PHP don't actually know 1 = one, so you can't iterate through it with a loop.
You have to provide this mapping to it, be it by switching instead of loads of ifs, or creating an array map.
Why not just create a array of items that are the 'lookup table' in the order need like:
$items = ['item_1', 'item_2', 'item_3', … 'item_n'];
or have a string of items like:
$items = explode('|', 'item_1|item_2|item_3|item_n');
//| being the delemiter or what ever might not occur inside any items
then have your $number (might need to minus 1 to $number if items start with 1 and so on to get correct item) used in the array to get the specific item without a loop like:
//$number = 3
$number--;
echo $items[$number];//echos 'item3'
but it almost seems like you then want something like:
//$number = 3
$items = explode('|', 'red|pink|gold|invisible');
echo ${$items[$number - 1]};
//translates into `echo $gold;`
//echos whatever is in $gold
Reading some of your comments it seems like you might be best off to rethink your logic/variables and use arrays and such instead of possibly hundreds of differently named variables that you have to check every time which can't be converted into a simple loop like you wish it could be. The only other possibly is using variables variables like many, including me, have mentioned but you seem to shoot them down. I wouldn't recommend variables variables personally but it would possibly speed up time without needing to do any looping. To effectively minimize code without the need of many if/elses you need to have logic that is consistent.
I think this is what you mean :
echo ${"file" . $number};
But that is showing variable for $filen, for example : $file1, file2, etc. If you want to make it as number, you can do like this :
echo ${"file" . intToEnglish($number)};
You can make intToEnglish(int $number) yourself or need us for help?
I'm not quite sure why you need to loop this, but if you really need to loop this, you can try this :
$i = 0;
while ($i !== $number) {
$i++;
}
echo ${"file" . intToEnglish($i)};
But, make sure that echo ${"file" . intToEnglish($number)}; is exist or you will go through infinite looping.
-- EDIT --
This is the case with your edited colour variable case. If you want to make it simple (looping), you muse change how your variable assingned. Example :
$colour = array("green","yellow","red","blue","black");
$i = 0;
while ($i !== $number) {
$i++;
}
echo $colour[$i];
Actually that looping is not really necessary until you have process inside it. You can just define it directly like this :
echo $colour[number];
-- EDIT 2 ---
This is with checking things :
while($i <= $number) {
if($i === $number) { echo $colour[number]; }
else { echo 'Checking'. $i; }
}
Loop is completly the wrong construct for your problem.
Use an array like so:
<?php
$number = 2;
$english = array("zero","one","two","three","four");
echo "file" . $english[$number];
?>
displays filetwo
After OP edit all becomes clear -- try:-
<?php
$number = 2;
$red = "crimson";
$clear = "glass";
$yellows = array("gold","lemon","acid","ochre");
$orange = "tangerine";
$black = "charcoal";
$objects = array(&$clear,&$red,&$yellows,&$orange,&$black);
var_dump( $objects[$number] );
?>
outputs:
array(4) { [0]=> string(4) "gold" [1]=> string(5) "lemon" [2]=> string(4) "acid" [3]=> string(5) "ochre" }

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Converting a Foreach to a for loop

I have a 3rd party script that loops through every returned value and echos it.
I want to limit the amount to 3 loops but am having issues.
current loop:
foreach($json->data as $v)
{
echo $v->from->name."<br>";
}
I want to do something like:
for ($i=0;$i<3;$i++)
{
echo $v->from->name."<br>";
}
Is there any work around without having to rework the whole script.
If $json is a integer-indexed array (although I doubt it)
for ($i=0;$i<3;$i++)
{
echo $json->data->from->name."<br>";
}
otherwise a less elegant solution would be
$i = 0;
foreach($json->data as $v)
{
echo $v->from->name."<br>";
if(++$i == 3) {break;}
}
finally
foreach(slice($json->data, 0, 3, TRUE) as $v)
{
echo $v->from->name."<br>";
}
No need to convert it in to for loop put an extra counter like this.
$count=0;
foreach($json->data as $v)
{
if ($count == 3)
{
break;
}
echo $v->from->name."<br>";
$count++;
}
Slice the first 3 elements off the array and loop over those.

Categories