Foreach issue

Hey,

With the folowing code, I get the last if statement back as the result no matter what $types matches… I want it to match the jpg file to each word in the array…


	$type = explode(",",$type);
	foreach($type as $types) {
	
	if($types = 'Wordmark') {	
		$l = 'wordmark.jpg';
	}
	if($types = 'Letterform') {
		$l = 'letterform.jpg';
	}
	if($types = 'Pictorial') {
		$l = 'pictoral.jpg';
	}
	if($types = 'Emblem') {
		$l = 'emblem.jpg';
	}
	if($types = 'Abstract') {
		$l = 'abstract.jpg';
	}

echo "$l<br />$types";


Thanks

=

:slight_smile:

Oh well that was embarrassing… I should have taken a break…

Thanks

You seem to have your variables backwards as well… $type for multiple types, and $types for a single type hardly makes sense.

Hi @matrix,

It just so happens that my latest project heavily involves matrixes/matrices

Maybe try this:



    $type = 'Wordmark, Letterform, Pictorial, Emblem, Abstract';
    $type = explode(',', $type);

    foreach($types as $id => $type):
      echo '<br />', $id, ': ', $type, ' ===> ', strtolower($type) . '.jpg';
    endforeach;


Output:

0: Wordmark ===> wordmark.jpg
1: Letterform ===> letterform.jpg
2: Pictorial ===> pictorial.jpg
3: Emblem ===> emblem.jpg
4: Abstract ===> abstract.jpg

Try this instead:


$incoming = "Letterform, Wordmark,Someoldcrap";
$allowed = array("Letterform","Wordmark", "Pictorial", "Emblem", "Abstract");

$types = explode(",",$incoming);
$results = ""; // declare the empty string

// as was pointed out get used to writing "foreach plural as singular" and you wont get mixed up
 foreach($types as $type) {
  if( in_array(trim($type), $allowed)){
    $results .= strtolower($type) . '.jpg for ' . $type . PHP_EOL;  // concat the string
  }
 }
 echo $results;

Your original code was flawed because you were forever overwriting any previous match.

This code concatenates a string, but could just as easily be returning an array.


    if($types = 'Pictorial') {
        $l = 'pictoral.jpg';
    }

When you see yourself writing things over and again Pictorial, pictorial alarm bells should go off in your head and you should ask “is there a better way?” Perhaps invest some real time in grokking how arrays work.

EDIT Gah, too slow, beaten by JB!