How can I convert String to an Array?
String bellow
$string = "12&Shoes&28&Jewelry&30&Watch&96&Beauty&98&Kids&Baby";
wants to output:
array{
[12] => 'Shoes',
[28] => 'Jewelry',
[30] => 'Watch',
[96] => 'Beauty',
[98] => 'Kids&Baby'
}
Can any one suggest me how can I convert it using php function? like preg_match,preg_match_all etc.also code should be short.
1) Convert String to Array using explode() explode() method is one of the built-in function in PHP which can be used to convert string to array. The explode() function splits a string based on the given delimiter. A delimiter acts as a separater and the method splits the string where the delimiter exists.
Implode in PHP is a function that is used to concatenate all the elements of an array together in the same order as they are in the array. And it, in turn, returns a new resultant string. This function is the same as the join() function in PHP, and both are an alias of each other.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
I know you asked for regex, but i'm the one who likes to do other way if it's simple to do.
$string = "12&Shoes&28&Jewelry&30&Watch&96&Beauty&98&Kids&Baby&Try";
$array = explode('&', $string);
$total = count($array);
for ($i = 0; $i < $total; $i++) {
if (is_numeric($array[$i])) {
$result[$array[$i]] = '';
$lastIndex = $array[$i];
} else {
if ($result[$lastIndex] == ''){
$result[$lastIndex] .= $array[$i];
} else {
$result[$lastIndex] .= '&' . $array[$i];
}
}
}
var_dump($result);
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