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?
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.
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 .
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.
Try this:
list($one, $two) = split("-", "44-xkIolspO", 2);
list($one, $two) = explode("-", "44-xkIolspO", 2);
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With