I have a variable that looks like this:
$var = "Dropdown\n
Value 1\n
Value 2\n
Value 3\n";
As you can see it's basically values broken by line breaks.
What I want to do is get the Option Type, in this case "Dropdown" and store the rest of the values in another string.
So
list($OptionType, $OptionValues) = explode("\n", $var);
The code above is what I tried but this is what the strings came out as:
$OptionType = 'Dropdown'; //Good
$OptionValues = 'Value 1'; // Only got the first value
I want $OptionValues to be like this: $OptionValues = "Value 1\nValue 2\nValue 3\n";
How would I do something like that?
The Option Type is always going to be the first part of the string followed by option values each seperated by a linebreak.
It's organized this way as it comes from user-input and it makes it much easier on the user to handle.
You need to use the third argument of explode()
, which sets the limit.
$var = "Dropdown\n
Value 1\n
Value 2\n
Value 3\n";
list( $foo, $bar ) = explode( "\n", $var, 2 );
echo $bar;
$values_array = explode("\n", $var);
$OptionType = $values_array[0];
unset($values_array[0]);
$OptionValues = implode("\n", $values_array);
You can use array_shift to automatically pop off the first exploded element, and then join the remaining.
<?
$var = "Dropdown\nValue 1\nValue 2\nValue 3\n";
$exploded = explode("\n", $var);
$OptionType = array_shift($exploded);
$OptionValues = join("\n", $exploded);
echo $OptionType . "\n";
print_r($OptionValues);
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