how to convert a string into an array in php
Solution:
You can use preg_match_all
(Regular Expression), and array_combine
:
RegEx used : ([^\/]*?)\/(\d+)
, eplanation here (by RegEx101)
$str = "php/127/typescript/12/jquery/120/angular/50";
#match string
preg_match_all("/([^\/]*?)\/(\d+)/", $str, $match);
#then combine match[1] and match[2]
$result = array_combine($match[1], $match[2]);
print_r($result);
Demo (with steps) : https://3v4l.org/blZhU
Answer
Solution:
One approach might be to use preg_match_all
to extract the keys and values from the path separately. Then, use array_combine
to build the hashmap:
$str = "php/127/typescript/12/jquery/120/angular/50";
preg_match_all("/[^\W\d\/]+/", $str, $keys);
preg_match_all("/\d+/", $str, $vals);
$mapped = array_combine($keys[0], $vals[0]);
print_r($mapped[0]);
This prints:
Array
(
[0] => php
[1] => typescript
[2] => jquery
[3] => angular
)
Answer
Solution:
You can use explode()
with for()
Loop as below:-
<?php
$str = 'php/127/typescript/12/jquery/120/angular/50';
$list = explode('/', $str);
$list_count = count($list);
$result = array();
for ($i=0 ; $i<$list_count; $i+=2) {
$result[ $list[$i] ] = $list[$i+1];
}
print_r($result);
?>
Output:-
Array
(
[php] => 127
[typescript] => 12
[jquery] => 120
[angular] => 50
)
Demo Here :- https://3v4l.org/8PQhd
Source