I have an array that I’m trying alter the output if a particular string is found.
As you can see below it successfully changes Upper Captiva to Captiva when the condition occurs but my else statement is ignored where it should simply show the $row[‘SUBDIVISION’] value if the condition does not occur.
I’ve tried adding $mycodes and $row[‘SUBDIVISION’] to the else line with no luck.
<?php
$mycodes = explode(",", $row['SUBDIVISION']);
$arr = array( "Upper Captiva" => "Captiva",);
$printedsomething=0;
foreach($mycodes as $code) {
if ($arr[$code] != '' ) {
if ($printedsomething==1) echo ", " . $arr[$code];
else echo $mycodes;
$printedsomething=1;
}
} //end for loop
?>
This is a code example as you asked for in the comments. If this does not work, please let me know so I can remove this answer.
But I don’t thik this is what you want. As far as I understand, you want to look if any of your codes ar in
$arr, and if so, echo them out, separated by a comma.Besides the fact that you can’t echo out an array (
$mycodes) (I guess you wanted to output$arr[$code]there), there’s probably a more elegant way, which would be to define an empty results array before the loop:Then you could put the relevant values in there, so the code between the stars would go like this:
So you could do this after the loop:
So the final code would look something like this:
Another, even more elegant approach would be using some of the countless array-functions PHP provides. For instance, if you just want to output only your distinct codes and filter them through another array, you could use array_flip() on
$mycodesin order to turn the values into keys. After that you could use array_intersect_key() to filter only the keys which are also present in$arr. That way, you could express the whole loop and its output in one line:I can’t tell if this works for you since I don’t know exactly what your arrays look like. Also I’m not sure if this meets your requirements.