Page 1 of 1

What am I missing here?

Posted: Mon Sep 12, 2011 6:00 pm
by someguyhere
I'm having trouble with the following code, and I know the correct data is here. For example, let's say both $category->category and $member_data[service_category] contain "Legal" - based on my understanding of strpos, this *should* make that field check. Am I missing something here?

Code: Select all

				foreach ($network_categories as $category) {
					$category_list .= '<input name="network_category_list[]" value="' . $category->category . '"';
						$check_cat = strpos($category->category, $member_data[service_category]);
						if($check_cat === true){
							$category_list .= ' type="checkbox" checked="checked" > ' . $category->category . "\n";
						} else {
							$category_list .= ' type="checkbox"> ' . $category->category . "<br />\n";
						}
				}

Re: What am I missing here?

Posted: Mon Sep 12, 2011 7:32 pm
by twinedev
You assumptions are wrong. See http://us2.php.net/strpos for full details.

With your code, you are checking for the existence of the entire contents of $member_data[service_category] within the value of $category->category This doesn't check to make sure both contain "Legal". At best it will match any $category->category value if $member_data[service_category] is exactly "Legal"

Next issues, you are doing if($check_cat === true) { this will NEVER happen. === means equal AND same data type, so $check_cat would have to be a boolean value TRUE, but strpos returns either a 0 or positive integer value, or the Boolean value of FALSE if not match.

What you really should have (assuming that you are still find with using strpos) is:

Code: Select all

if ($check_cat !== FALSE) {
This will give you the results you are looking for.

Note, some people would try to just use

Code: Select all

if ($check_cat == TRUE) {
as this just says if $check_cat evaluates to a TRUE value, however if the match is on the beginning of the string, it would be 0, which evaluates to FALSE.

-Greg