1

Can anyone lend me a suggestion on why my code below doesn't work? What I want to accomplish is if $value1 == '0' is true, then concatenate the value/text that correspond to the key order in $stdArray2. I'm not sure if this is the best or right way to do it. Is there a better way? The code seems clumpsy but can't complain much since my coding skill is pretty bad.

My PHP

$stdArray1 ['1']  = $orange;
$stdArray1 ['2']  = $apple;
$stdArray1 ['3']  = $peach;
$stdArray1 ['4']  = $berry;
$stdArray2 ['1']  = 'Flordia';
$stdArray2 ['2']  = 'Washington';
$stdArray2 ['3']  = 'Georgia';
$stdArray2 ['4']  = 'Oregon';

foreach($stdArray1 as $value1){
  if($value1 == '0'){
    foreach($stdArray2 as $value2){
      $fruit .= $value2', ';
    }
  }
}
1
  • Do you want concatenate the corresponding second array value to first one? Commented Feb 10, 2018 at 4:30

2 Answers 2

1

If you just want the corresponding value in the second array, you shouldn't use a second loop, just use an array index.

foreach ($stdArray1 as $index => $value) {
    if ($value == '0') {
        $fruit .= $stdArray2[$index] . ", ";
    }
}

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

Your code should be like this:

foreach($stdArray1 as $value1){
  if($value1 == '0'){
    foreach($stdArray2 as $value2){
      $fruit .= $value2.', ';
    }
  }
}

You are missing . in foreach loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.