SherwoodPro
SherwoodPro

Reputation: 105

Strings and Arrays not working like I thought

I'm trying to learn more about strings and arrays. I have this bit of code:

<?php
$states = "OH, VA, GA";
$arrayStates = explode(",", $states);
$exists = "GA";
print_r($arrayStates);

if (in_array($exists, $arrayStates)){
    echo "<br/>" . $exists . " " . "exists.";
} else {
    echo "<br/>" . $exists . " " . "doesn't exist.";
}
?>

According to my feeble mind, GA should exist in the array. If I put $exists = "OH", that works. But the screen is showing this:

Array ( [0] => OH [1] => VA [2] => GA ) 

GA doesn't exist.

What am I not understanding here?

Upvotes: 0

Views: 74

Answers (6)

Fernando Prieto
Fernando Prieto

Reputation: 520

In $arrayStates after applying explode(...) you have:

$arrayStates[0] stores "OH"
$arrayStates[1] stores " VA"
$arrayStates[2] stores " GA"

Note at index 2 the array is storing " GA" (note the space) instead of "GA" that is because in the explode function you are using ",". To get your code working as you want you should use in the explode function ", " (note the space)

Upvotes: 1

hae
hae

Reputation: 216

The explode method splits the string on the comma "," ONLY and does not remove the whitespace. As a result you end up comparing "GA" (your $exists) to " GA" (inside of the array, note the whitespace) =]

Upvotes: 0

user568109
user568109

Reputation: 48003

That is because it is being divided by , so your array contents are :

Array
(
    [0] => OH
    [1] =>  VA
    [2] =>  GA
)

you need to do $arrayStates = explode(", ", $states);

Upvotes: 1

Iłya Bursov
Iłya Bursov

Reputation: 24146

you're splitting with , but your text has spaces, so after split you have:

Array ( [0] => OH [1] => _VA [2] => _GA )

you can either split by ,_ (replace underscore with space)

or you can trim all values after split, like:

foreach ($arrayStates as $k => $v) $arrayStates[$k] = trim($v);

Upvotes: 1

Barmar
Barmar

Reputation: 781096

The array contains the string " GA" with a space as the first character. That's not equal to `"GA", which goesn't have a space.

You should either use explode(", "), $states) or call trim() on each element of the array:

$arrayStates = array_map('trim', explode(",", $states));

Upvotes: 5

kdazzle
kdazzle

Reputation: 4300

You need to explode with a space after the comma.

$arrayStates = explode(", ", $states);

Upvotes: 1

Related Questions