How do I output a variable in an array foreach?

Hi. Need to find a variable in an array, then check for its existence

An array like this
$good[spec] = array('mall', 'discount', 'promotion');

Doing so
foreach($good[spec] as $mall){
 if($mall == 'mall'){
 $rate_mall .= 'mall';

if($rate_mall) {
 echo 'Yes';
 } else {
 echo 'No';

when you run this code I have an infinite set YES is displayed even if $mall == 'mall' does not exist. Where I erred?
July 2nd 19 at 13:52
1 answer
July 2nd 19 at 13:54
Apparently you cycle pass for all goods?

What is the spec? In your example it's constant, I assume this is the problem.

Probably the spec should be variable:

$good[$spec] = array('mall', 'discount', 'promotion');
// ^

foreach($good[$spec] as $mall) {
 // ^
 // ...


UPD: the theory of the constant was incorrect and in this case, spec is interpreted as a literal string, but it is not recommended:
Why is $foo[bar] wrong?

Always use quotes around a string literal in the index of the associative array. For example, write $foo['bar']and not $foo[bar]. But why? Often in old scripts you can find the following syntax:

$foo[bar] = 'enemy';
echo $foo[bar];
// etc.

This is incorrect, although it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). It works because PHP automatically converts a "naked line" (not enclosed in a quoted string, which does not correspond to any known language symbols) in a string with the value of this "naked line". For example, if the constant named bar is not defined, PHP will replace the bar to the string 'bar' and use it.
unfortunately the spec is not constant - Clotilde_Bogan56 commented on July 2nd 19 at 13:57
If it is not constant, then You have an error in sintaxis. Why not take advantage of poskom the array? - Turner.Hackett commented on July 2nd 19 at 14:00
: If $rate_mall has some value, then the output will be Yes. Otherwise, No.

If $rate_mall is located in a loop at the first found matching value of the variable will not be NULL , and for each iteration of the loop the output will be Yes:

If you remove $rate_mall, then Yes it will be only where a match is found: - Toney_Pur commented on July 2nd 19 at 14:03
thanks, you all helped out. - Clotilde_Bogan56 commented on July 2nd 19 at 14:06

Find more questions by tags PHP