Jump to content

Split a variable if it has a delimiter


mminten

Recommended Posts

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

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.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.