“foreach”导致我的功能行为不端

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);
    }

?>