Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Convert a string to an array

Tags:

arrays

php

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.

like image 346
R P Avatar asked May 29 '17 19:05

R P


People also ask

Which function in PHP allows you to convert a string to an array?

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.

What is implode PHP?

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.

What is explode in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.


1 Answers

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);
like image 114
capcj Avatar answered Nov 13 '22 16:11

capcj