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
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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.