June 17, 2010

Check variable if explode-able in PHP

Question by ZaneDeFazio

Not sure if there is a way to check a variable if it is explode-able or not…

I have a database of city names some are one word cities and some are multiple word cities

EX: Chicago, Los Angeles

I keep getting an error when use “implode” when a city name is one word, so I tried using “count” and using an if statement… not having any luck

$citi = explode(' ', $row['city']);
$count = count($citi);
if ($count > 1) {
   $city = implode('+', $citi);
}
else {
   $city = $citi;
}

Answer by Ben Rowe

if(strpos($row['city'], ' ') !== false) {
  // explodable
} else {
  // not explodable
}

Answer by Starx

use explode itself to see if it is explodable

$a = explode(" ","Where Am I?");
if(count($a)>1) {
     echo "explodable";
}
else {
     echo "No use of exploding";
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!