"foreach" causes my function to misbehave - php

I'm trying to make the following work:
<?php
$item1 = A;
$item2 = B;
$item3 = C;
$array = array($item1, $item2, $item3);
function myFunction () {
if ($item = "A") {
echo "Alpha ";
}
elseif ($item = "B") {
echo "Bravo ";
}
elseif ($item = "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ();
}
?>
The intended effect is that for each item, if the value is A, echo "Alpha", B echo "Bravo" and C echo "Charlie".
However, the output is as follows:
Alpha Alpha Alpha
There were no errors in the error log, so I'm guessing I must have made some kind of mistake not pertaining to syntax. I added an echo $item; before myFunction, and the output is as follows:
AAlpha BAlpha CAlpha
Which means that the $item has been correctly assigned A, B and C. Why doesn't myFunction work like intended?
Thanks in advance!

1) The = is the assignment operator and may not be used for comparisons. Try == or === instead.
2) You assigned $item1 = A but compared $item = "A". However A and "A" are usually different.
3) You didn't pass $item to the function.
In the first if statement you assign "A" to $item and then print out "Alpha" “if "A"”.
Your code should probably look something like this:
<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>

Set $item parametar on your function.
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction($item){
if($item == "A"){
echo 'Alpha'.'<br/>';
}
elseif ($item == "B") {
echo 'Bravo'.'<br/>';
}
elseif ($item == "C") {
echo 'Charlie'.'<br/>';
}
}
foreach ($array as $item) {
myFunction($item);
}

Also, are you going to pass the variable to your function or what? Otherwise, as it is right now, it should only output "error."
Your function does not have an argument.
foreach ($array as $item) {
myFunction ();
}
How about passing the $item so that your function can actually work:
function myFunction($item) {
and therefore:
foreach($array as $item) {
myFunction($item);
}

<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>

Related

PHP, Echo only one time in a foreach loop

i'have an array, and then i have a script who gets the category i'm browsing (using wordpress) and put it in the $category variable.
So i test if the category i'm browsing it's equal to the $array key and then i paste some text
$array = array ('key' => 'value', ... )
//...
// a script who gets the category i'm browsing and store it in the $category variable
//...
/* starting the foreach loop */
foreach( $array as $key => $value) {
if ($category == $key) {
echo "some $value here";
} elseif ($category !== $key) {
echo "nothing";
}
The problem is that this loop does echo "nothing" for each time the $category is not equal to the $key for each element of the array.
So if i have 20 key => value in the array this loop paste one time "some $value here" and 19 times "nothing"
there is a way to echo "nothing" only one time?
Thank you!
You can use array_key_exists instead of the foreach loop:
if (array_key_exists($category, $array)) {
echo $array[$category];
} else {
echo 'nothing';
}
$i=0;
foreach( $array as $key => $value) {
$i++;
if ($category == $key) {
echo "some $value here";
} elseif($category !== $key)
{
if($i<=1)
{
echo "nothing";
}
else{}
}
Try with -
$i = 1;
foreach( $array as $key => $value) {
if ($category == $key) {
echo "some $value here";
} elseif ($category !== $key) {
$i++;
}
}
if (count($array) == $i) {
echo "nothing";
}

PHP output only one value in for each

I'm having trouble with output in for each function in PHP (actually don't know how to set the code to do what I need). I'd like to output some text if every item in foreach is equal to some value. If I put
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
I will get true for every item and I need to output true only if all items are equal to some value.
Thanks!
This is most likely due to PHP type juggling your values. Your values are probably not numeric so when you do a loose comparison (==) PHP converts them to integers. Strings that do not start with digits will become zero and your statement will be true.
To fix this use the === comparison operator. This will compare value and type. So unless a value is the integer zero it will be false.
if($item === 0){ echo "true"; }
If you are trying to see if all items are equal to some value this code will do this for you:
$equals = 0;
$filtered = array_filter($items, function ($var) use ($equals) {
return $var === $equals;
});
if (count(count($items) === count($filtered)) {
echo "true";
}
This peice of code work for most type of variables. See how it works in inline comment.
$count=0; // variable to count the matched words
foreach ($items as $item)
{
if($item == $somevalue)
{
$count++; // if any item match, count is plus by 1
}
}
if($count == count($items))
{
echo "true"; // if numbers of matched words are equal to the number of items
}
else
{
echo "false";
}
Hope it works , And sorry for any mistake
$ok = true;
foreach ($items as $item)
{
if ($item != 0)
{
$ok = false;
}
}
if ( $ok == true)
{
echo 'true';
}
$bool = 0;
foreach($items as $item) {
if($item == $unwantedValue)
{ $bool=1; break; }
}
if($bool==0)
echo 'true';
$equals=true;
foreach($items as $item) {
if($item!=0)
{
$equals=false;
break;
}
}
if($equals) {
echo 'true';
}
if you want to check the values is same with some value in variabel and print it use this
<?php
$target_check = 7;
$items = array(1, 4, 7, 10, 11);
foreach ($items as $key => $value) {
if ($value == 7) echo "the value you want is exist in index array of " . $key . '. <br> you can print this value use <br><br> echo $items[' . $key . '];';
}
?>
but if you just want to check the value is exist in array you can use in_array function.
<?php
$target_check = 2;
if (in_array($target_check, $items)) echo "value " . $target_check . 'found in $items';
else echo 'sorry... ' . $target_check . ' is not a part of of $items.';
?>
<?
$items=array(0,1,2,0,3,4);
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
?>
your code work!
check the source of the $items array

Getting a particular array and echo its value

I have this script from a free website file. Here is the subject script:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
How to get the value of ID and echo it?
When you clean up the code, it’s easy to see how to access the ID value:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
if ($a == 'ID') {
echo $a1;
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
Just adding the check for ID will work:
if ($a == 'ID') {
echo $a1;
}
EDIT And if you want to access it outside of the foreach loop, just do this. I have an if conditional to just check if the value exists.
if (array_key_exists('ID', $auth) && !empty(trim($auth['ID'])) {
echo $auth['ID'];
}
Or, since your foreach loop is creating $results you can access that value this way instead:
if (array_key_exists('ID', $results) && !empty(trim($results['ID'])) {
echo $results['ID'];
}

Variable variables created within a for loop

I'd like to change this:
if ($week_day == "1")
{
$day1_hours = $value;
}
if ($week_day == "2")
{
$day2_hours = $value;
}
if ($week_day == "3")
{
$day3_hours = $value;
}
if ($week_day == "4")
{
$day4_hours = $value;
}
if ($week_day == "5")
{
$day5_hours = $value;
}
if ($week_day == "6")
{
$day6_hours = $value;
}
if ($week_day == "7")
{
$day7_hours = $value;
}
}
Into something more readable, like a for loop, or whatever other suggestions you all may have.
I tried to do:
for ($c=1; $c<8, $c++)
{
if ($week_day == $c)
{
$day".$c."_hours = $value;
}
}
But I know that is nowhere near correct, and I have no idea how to insert another variable within a variable.
Any help is appreciated!
Try this syntax.
${'day'.$c.'_hours'} = $value;
Try this
$hours[$week_day] = $value
Something like this
$week_day = 3;
$value = "hi";
${"day" . $week_day . "_hours"} = $value;
echo $day3_hours;
My interpretation.
$week = 7;
$day = array();
for($i=1; $i<=7; $i++){
$day[$i]['hours'] = $value;
}
You can declare the numbers of weeks you want and to pull the data you can do something like this:
echo $day[1]['hours']

How to simplify if conditions?

How can I simplify if conditions, because per each condition I make a new if/elseif and its a lot of code, this is what I have:
$chapters = array('1:data1', '2:data2', '4:datax', '3:datag');
sort($chapters);
$screenshots = array('1:screen1', '2:screen2', '3:screen3', '4:go4');
$chapterCount = count($chapters);
$chapterItems = 0;
foreach ($screenshots as $key => $screenshot) {
$screenshotInfo = explode(':', $screenshot);
$screen[$screenshotInfo[0]] = $screenshotInfo[1];
}
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
// If is the first chapter
if ($chapterNumber == 1) {
echo '<li>'.$chapterInfo[0].'</li>';
// If have only one chapter
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
}
// If is a new chapter
elseif ($currentNumber != $chapterNumber) {
echo '<li>'.$screen[$chapterNumber-1].'</li>';
echo '<li>'.$chapterInfo[0].'</li>';
// If is new and last chapter
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
}
// If is the last chapter
elseif ($chapterItems+1 == $chapterCount) {
echo '<li>'.$chapterInfo[0].'</li>';
echo '<li>'.$screen[$chapterNumber].'</li>';
}
else {
echo '<li>'.$chapterInfo[0].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
That code works perfect on my tests but I'm sure it have a lot of unneeded code.
If brevity is of more interest than readability, you can use ternary statements.
$foo = true;
$bar = $foo ? 'something' : 'nothing';
echo $bar;
//returns 'something'
$foo = false;
$bar = $foo ? 'something' : 'nothing';
$echo bar;
//returns 'nothing'
May be you could use a function for all the if-conditions. Since all the if-conditions inside are same we could use something like:
$chapters = array('1:data1', '2:data2', '4:datax', '3:datag');
sort($chapters);
$screenshots = array('1:screen1', '2:screen2', '3:screen3', '4:go4');
$chapterCount = count($chapters);
$chapterItems = 0;
foreach ($screenshots as $key => $screenshot) {
$screenshotInfo = explode(':', $screenshot);
$screen[$screenshotInfo[0]] = $screenshotInfo[1];
}
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
if ($chapterNumber == 1) { // If is the first chapter
echo '<li>'.$chapterInfo[0].'</li>';
echo compare($chapterItems,$chapterCount,$screen,$chapterNumber); // If have only one chapter
} elseif ($currentNumber != $chapterNumber) { // If is a new chapter
echo '<li>'.$screen[$chapterNumber-1].'</li>';
echo '<li>'.$chapterInfo[0].'</li>';
echo compare($chapterItems,$chapterCount,$screen,$chapterNumber); // If is new and last chapter
} elseif ($chapterItems+1 == $chapterCount) { // If is the last chapter
echo '<li>'.$chapterInfo[0].'</li>';
echo '<li>'.$screen[$chapterNumber].'</li>';
} else {
echo '<li>'.$chapterInfo[0].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
function compare($chapterItems,$chapterCount,$screen,$chapterNumber) {
if ($chapterItems+1 == $chapterCount) {
return '<li>'.$screen[$chapterNumber].'</li>';
}
return false;
}
Hope this helps you :)
If you check the original code you will see that:
echo '<li>'.$chapterInfo[0].'</li>';
will be printed in every scenario. So we don't actually need an if for that.
The only checks you need is:
isNew and not isFirst
if ($currentNumber != $chapterNumber && $chapterNumber != 1)
so we can print the 'new header':
echo '<li>'.$screen[$chapterNumber-1].'</li>';
And if it's the last one, so we can print the last item footer:
echo '<li>'.$screen[$chapterNumber].'</li>';
So we can simplify by having the bellow code:
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
// If is new AND is not the first print the 'New item header'
if ($currentNumber != $chapterNumber && $chapterNumber != 1) {
echo '<li>'.$screen[$chapterNumber-1].'</li>';
}
// This was being printed in every scenario, so we don't need a if for that
echo '<li>'.$chapterInfo[0].'</li>';
// If it is the last, print the 'Last item footer'
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
if your goal is just to remove if/else and get easier code coverage you can do the same thing but only with ternaries like that:
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
echo ($currentNumber != $chapterNumber && $chapterNumber != 1) ? sprintf('<li> %s </li>', $screen[$chapterNumber - 1]) : '';
echo sprintf('<li> %s </li>', $chapterInfo[0]);
echo ($chapterItems + 1 == $chapterCount)? sprintf('<li> %s </li>', $screen[$chapterNumber]): '';
$currentNumber = $chapterNumber;
$chapterItems++;
}

Categories