17

Say I have the following: "44-xkIolspO"

I want to return 2 variables:

$one = "44";
$two = "xkIolspO";

What would be the best way to do this?

Vincent Ramdhanie
  • 98,815
  • 22
  • 134
  • 183
Latox
  • 4,442
  • 15
  • 44
  • 73
  • Remember, the manual lists every function you could ever want: http://php.net/ref.strings – Jonah Jan 19 '11 at 03:17
  • Well, unless you know how many variables you must get, `list()` may render quite useless. Manual assignment is better. In such cases, use a `foreach()` to create an array of values. – Fr0zenFyr Apr 11 '19 at 05:56

2 Answers2

38

Try this:

list($one, $two) = split("-", "44-xkIolspO", 2);

list($one, $two) = explode("-", "44-xkIolspO", 2);
Chandu
  • 74,913
  • 16
  • 123
  • 127
  • 1
    Awesome, except that [split is deprecated](http://php.net/manual/en/function.split.php). A more future-proof solution would probably be [explode](http://php.net/manual/en/function.explode.php). – sdleihssirhc Jan 19 '11 at 03:05
  • use preg_split("/-/", "44-xkIolspO"); – Mihai Toader Jan 19 '11 at 03:07
  • 1
    Updated the post to use explode. Hope its not deprecated yet. – Chandu Jan 19 '11 at 03:07
  • 1
    According to http://micro-optimization.com/explode-vs-preg_split using preg_split is 69% faster. – Mike Kormendy Nov 06 '14 at 22:37
  • 1
    @MikeKormendy when you read the article it says "f2 is slower than f1 by 68.73% " where f2 is the preg_split and f1 is the explode. So, unless I'm missing something obvious, the article is saying that explode is 69% fater than preg_split – philip May 22 '17 at 18:16
8

PHP has a function called preg_split() splits a string using a regular expression. This should do what you want.

Or explode() might be easier.

    $str = "44-xkIolspO";
    $parts = explode("-", $str);
    $one = $parts[0];
    $two = $parts[1];
Alix Axel
  • 141,486
  • 84
  • 375
  • 483
Vincent Ramdhanie
  • 98,815
  • 22
  • 134
  • 183
  • I don't think preg_split is anywhere near necessary in this case. Regular expression parsing is much less efficient than a delimiter string. – Jonah Jan 19 '11 at 03:15