Forum Moderators: coopster

Message Too Old, No Replies

tricky == matching: how to deal with a space?

         

zozzen

8:26 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



Hi,

I'm using if ($a == $b) to see if $a matches $b, but it seems that there's a problem.

First, I set an array:

$cat = "Asia,America,Europe,Africa,Middle East";
$catlist = explode(",", $cat_a);


Now, I got this:


$catlist[0] = Asia
[1] = America
[2] = ...
[4] = Middle East


Then I would like to see if it matches any $category:


if ($catlist[$i]==$category)
$answer = "yes";


All strings work very well, except the word "Middle East". If i remove the space, it will work again.

How should i deal with the space in this string?

Please advise. Thanks a lot!

jatar_k

8:40 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



in your particular case you would probably be better to use strcmp [php.net]

I guess you could also try
in_array [php.net]
or
array_search [php.net]

Matthew1980

8:41 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there zozzen,

Whats the contents of $category? or is that user generated?

Also:-

$cat = "Asia,America,Europe,Africa,Middle East";
$catlist = explode(",", $cat_a);

Are you missing the _a from the first var? Looks odd on first glance ;)

Cheers,
MRb

Demaestro

8:41 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Replace the spaces when comparing.

if (str_replace(' ', '', $catlist[$i]) == $category)

zozzen

9:11 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



Thanks a lot for everyone! I spent my whole night trying to see what's wrong but you guys made it within a few minute! Really big thanks!

This one works:
if (!strcasecmp($catlist_a[$i], $category) == 0 )

This one is easier for me to understand but mysteriously doesn't work in my case.
if (str_replace(' ', '', $catlist_a[$i]) == $category)

Matthew, I made a mistake on posting the code. The original code is correct.
The $category is the string for mediawiki's category, but unlike other mediawiki, I want to preset all categories and let users choose it.

Matthew1980

9:30 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there zozzen,

I am still spending all night on my issue! I'll get there though - hopefully ;)

I wonder if you changed that comparison around would it do the trick? :-

if($category == str_replace(' ','', $catlist_a[$i]))

as you are comparing $category against the array - though I doubt it makes much difference...

Glad your sorted anyway.

Cheers,
MRb