954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Check array for word, if true do something. Errors...

What I'm trying to do is take an array that I created and look for key abbreviations in that array, if it finds something it will append a variable until all item in the array have been found, then returns the appended variable.

Having trouble with it though...

function check_programs($input) {
		// Replaces the array with longer string.
		$programs = array($input);
		$check = 0;
		$return_string = '';
		while ($check <= $programs){
			if(array_search('ma', $programs) == true){
				$return_string .= "Maya, ";
				$check ++;
			}elseif(array_search('ps', $programs) == true){
				$return_string .= "Photoshop, ";
				$check ++;
			}elseif(array_search('ai', $programs) == true){
				$return_string .= "Illustrator, ";
				$check ++;
			}elseif(array_search('xn', $programs) == true){
				$return_string .= "xNormal, ";
				$check ++;
			}else(array_search('mm', $programs) == true){
				$return_string .= "MatchMover, ";
				$check ++;
			}
			return $return_string;
		}
Eblahmysuper
Newbie Poster
4 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

Two points have to be noted here:

1. if you use else if conditional loop then it will go for only on condition for your input,then other matched inputs will not return strings.
2.decide your input manner, whether it is in comma separated or space separated or some thing else. Based on this explode an array called $programs using php explode function.

and also:

-> Use in_array() instead of array_search for searching string in an array.
-> remove while loop, no use here.

based on the above things i have changed your code accordingly.try with the following:

<?php
function check_programs($input)
{
		$programs = explode(" ", $input);
		$return_string = '';
		if(in_array('ma', $programs) == true){
			$return_string .= "Maya, ";
		}if(in_array('ps', $programs) == true){
				$return_string .= "Photoshop, ";
		}if(in_array('ai', $programs) == true){
				$return_string .= "Illustrator, ";
		}if(in_array('xn', $programs) == true){
				$return_string .= "xNormal, ";
		}
		if(in_array('mm', $programs) == true){
				$return_string .= "MatchMover, ";
		}
		return $return_string;
		
}
echo $string1=check_programs('ps xn');
?>

If your requirement not matches this come up with clear information.

thanks.

Shanti C
Posting Virtuoso
1,642 posts since Jul 2008
Reputation Points: 137
Solved Threads: 162
 

Yes!! Thank you very much, the changes finally made the dang thing work!

Thank you for your help!

Eblahmysuper
Newbie Poster
4 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: