1

Wi, I have string:

sortAfter=1&searchString=vsfweew

How can I convert it to array:

Array
(
    [sortAfter] => 1
    [searchString] => vsfweew
)

?

3 Answers3

1
$str = 'sortAfter=1&searchString=vsfweew';
parse_str($str, $arr);
print_r($arr);
  • You posted answer after 10 min that is exact duplicate of @12emam answer. – Mohammad Oct 13 '18 at 07:25
  • @Mohammad answer of *12emam* is just plagiarized example from PHP docs. Specifically Example #1 from the PHP docs: php.net/manual/en/function.parse-str.php – Madhur Bhaiya Oct 13 '18 at 07:31
1
$str = 'sortAfter=1&searchString=vsfweew';

parse_str($str, $arr);
Sheetal Mehra
  • 478
  • 3
  • 13
0

While parse_str() is certainly convenient, there is another option using preg_split() as follows:

<?php

$str = "sortAfter=1&searchString=vsfweew";

list($e1,$sortAfter,$e2,$searchString) = preg_split("/=|&/",$str);
$arr[$e1] = $sortAfter;
$arr[$e2] = $searchString;
print_r($arr);

See live code

Preg_split() splits a string into an array whose values can then be assigned to a list of variables which include in this case variables that correspond to element names while others refer to element values. The list variables are then used to build a new array $arr.

slevy1
  • 3,797
  • 2
  • 27
  • 33