mminten Posted May 16, 2011 Share Posted May 16, 2011 I am trying to split a variable only if it has an integer. Here is what I want to do: $id = 1234-54678; should be split into and then placed into two variables: $id1 = 54678; $id2 = 1234; Sometimes the variable may not have a delimiter in which case I would like it to be $id1 example: $id = 54678; should go directly to $id1 = 54678; I am a php rookie and don't know which way is best to do this (explode, split, etc.) so I would appreciate any help you can give me. Link to comment https://forums.phpfreaks.com/topic/236593-split-a-variable-if-it-has-a-delimiter/ Share on other sites More sharing options...
DavidAM Posted May 17, 2011 Share Posted May 17, 2011 Use strpos $id = 1234-54678; if (strpos($id, '-') !== false) { list($id1, $id2) = explode('-', $id); } else { $id1 = $id; } Note the two equal-signs in the IF statement. strpos will return FALSE if the delimiter is not found; but it may also return zero (which would evaluate to false using !=) if the delimiter is at the beginning of the string. Link to comment https://forums.phpfreaks.com/topic/236593-split-a-variable-if-it-has-a-delimiter/#findComment-1216286 Share on other sites More sharing options...
requinix Posted May 17, 2011 Share Posted May 17, 2011 I like to cheat: list($id1, $id2) = explode("-", $id . "-"); Link to comment https://forums.phpfreaks.com/topic/236593-split-a-variable-if-it-has-a-delimiter/#findComment-1216299 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.