Jump to content

How would I use a switch case statement to run through an array?


Stuart_Westgate

Recommended Posts

I'm trying to use an array to go through a switch case statement.

This is my code at present but I feel something is missing as it's not working > Can someone please help?

 

 

$stringArray = array('socks:', '', 'jacket', 'boxers', 'trainer', 'tshirt', 'bag', 'tie');

 

$pos = strpos($statusItemCheck, $stringArray[0]);

 

$imageValue = "images/"; //Value of

 

switch($pos){

case $stringArray[0]:

$imageValue .= "socks.PNG";

break;

case $stringArray[1]:

$imageValue .= "hat.PNG";

break;

case$stringArray[2]:

$imageValue .= "jacket.PNG";

break;

default:

$imageValue .= "questionMark.PNG";

break;

}

Try something like this:

<?PHP

//### Set this for testing purpose
$statusItemCheck = 'jacket';

//### Path of images
$imageValue = 'images/';

//### Array of items
$stringArray = array('socks' => 'socks.png',
				 'hat' => 'hat.png',
				 'jacket' => 'jacket.png',
				 'boxers' => 'boxers.png'
				 );

//### Check if the item exists in the array
if(!isSet($stringArray[$statusItemCheck])) {
echo 'Item does not exist.';

//### Item exists, add the image filename to image value
} else {	
$imageValue .= $stringArray[$statusItemCheck];

echo $imageValue;
}

?>

If the pics are always going to have the standard name format of "item".png, you could do this

 

$availableItemsArray = ("socks", "jacket", "hat", "boxers");

 

$testItemsArray = ("jacket", "boxers", "monkey hair gloves", "socks", "jodhpurs");

 

$arrayLength = count($itemsArray); // you could put this in the for loop below .. but its better to only count the array one time and save it, than to count it on each iteration

 

for($i=0; i < $arrayLength; $i++){

 

 

if(in_array($testItemsArray[ $i ], $availableItemsArray) // grabs each item to be compared one by one .. and looks if it is in the array of available items

{

echo "images/" . $testItem[ $i ] . ".png";

}else{

echo "Item doesn't exist";

}

 

}

 

 

You might want to put a strtolower() in there somewhere to deal with capitalization discrepencies

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.