开发者

Check variable if explode-able in PHP

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 wo开发者_StackOverflow社区rd, 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;
}


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


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";
}


explode() always returns an array, whether it exploded something or not.

$a = explode(' ', 'Chicago');
print_r($a); 
// output: array('Chicago')


Yes, definitely can be done. Try stristr()

if( stristr( $row['city'], ' ' ) )
    // It has a space, therefore explodable

It loos like you're trying to turn the spaces into '+'.

I would just use a str_replace()

$city = str_replace( ' ', '+', $row['city'] );


This is the most efficient way. I have implemented this.

$name = $_POST["address_name"];
if(strpos($row['city'], ' ') !== false) {
  // explodable
  list($fname, $lname) = explode(' ', $name);
} else {
  // not explodable
  $fname = $name;
  $lname = $name;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜