Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split into two variables?

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?

like image 518
Latox Avatar asked Jan 19 '11 03:01

Latox


People also ask

How do I split a string into multiple variables?

To split string variables at each whitespace, we can use the split() function with no arguments. The syntax for split() function is split(separator, maxsplit) where the separator specifies the character at which the string should be split. maxsplit specifies the number of times the string has to be split.

Can split () take two arguments?

split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .

Can I assign 2 variables at once?

Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.


2 Answers

Try this:

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

list($one, $two) = explode("-", "44-xkIolspO", 2);
like image 109
Chandu Avatar answered Oct 13 '22 22:10

Chandu


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];
like image 26
Vincent Ramdhanie Avatar answered Oct 13 '22 23:10

Vincent Ramdhanie