Reputation: 3546
I have this:
$strVar = "key value";
And I want to get it in this:
array('key'=>'value')
I tried it with explode(), but that gives me this:
array('0' => 'key',
'1' => 'value')
The original $strVar is already the result of an exploded string, and I'm looping over all the values of the resulting array.
Upvotes: 43
Views: 85873
Reputation: 2308
Not sure this is really an answer but it took me some time to figure out so I'm going to share this anyway.
I wanted to change
Array
(
[0] => email= [email protected]
[1] => name = Joeri
[2] => token= AB2240824==
)
into
Array
(
[email] => [email protected]
[name] => Joeri
[token] => AB2240824==
)
And got that solved with:
$values = array_combine(
array_map(fn($v) => trim(explode("=", $v, 2)[0]), $values),
array_map(fn($v) => trim(explode("=", $v, 2)[1]), $values)
);
Hope this helps someone.
Upvotes: 0
Reputation: 21668
I am building an application where some informations are stored in a key/value string.
tic/4/tac/5/toe/6
Looking for some nice solutions to extract data from those strings I happened here and after a while I got this solution:
$tokens = explode('/', $token);
if (count($tokens) >= 2) {
list($name, $val) = $tokens;
$props[$name] = $val;
}
if (count($tokens) >= 4) {
list(, , $name, $val) = $tokens;
$props[$name] = $val;
}
if (count($tokens) >= 6) {
list(, , , , $name, $val) = $tokens;
$props[$name] = $val;
}
// ... and so on
freely inspired by smassey's solution
This snippet will produce the following kinds of arrays:
$props = [
'tic' => 4,
];
or
$props = [
'tic' => 4,
'tac' => 5,
];
or
$props = [
'tic' => 4,
'tac' => 5,
'toe' => 6,
];
my two cents
Upvotes: 0
Reputation: 5
If you have more values in a string, you can use array_walk()
to create an new array instead of looping with foreach()
or for()
.
I'm using an anonymous function which only works with PHP 5.3+.
// your string
$strVar = "key1 value1&key2 value2&key3 value3";
// new variable for output
$result = array();
// walk trough array, add results to $result
array_walk(explode('&', $strVar), function (&$value,$key) use (&$result) {
list($k, $v) = explode(' ', $value);
$result[$k] = $v;
});
// see output
print_r($result);
This gives:
Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)
Upvotes: -1
Reputation: 101
I found another easy way to do that:
$a = array_flip(explode(' ', $strVal));
Upvotes: -2
Reputation: 11
list($array["min"], $array["max"]) = explode(" ", "key value");
Upvotes: 1
Reputation: 2711
If you have long list of key-value pairs delimited by the same character that also delimits the key and value, this function does the trick.
function extractKeyValuePairs(string $string, string $delimiter = ' ') : array
{
$params = explode($delimiter, $string);
$pairs = [];
for ($i = 0; $i < count($params); $i++) {
$pairs[$params[$i]] = $params[++$i];
}
return $pairs;
}
Example:
$pairs = extractKeyValuePairs('one foo two bar three baz');
[
'one' => 'foo',
'two' => 'bar',
'three' => 'baz',
]
Upvotes: 0
Reputation: 101
$my_string = "key0:value0,key1:value1,key2:value2";
$convert_to_array = explode(',', $my_string);
for($i=0; $i < count($convert_to_array ); $i++){
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
Outputs array
$end_array(
[key0] => value0,
[key1] => value1,
[key2] => value2
)
Upvotes: 10
Reputation: 21
You can try this:
$keys = array();
$values = array();
$str = "key value";
$arr = explode(" ",$str);
foreach($arr as $flipper){
if($flipper == "key"){
$keys[] = $flipper;
}elseif($flipper == "value"){
$values[] = $flipper;
}
}
$keys = array_flip($keys);
// You can check arrays with
//print_r($keys);
//print_r($values);
foreach($keys as $key => $keyIndex){
foreach($values as $valueIndex => $value){
if($valueIndex == $keyIndex){
$myArray[$key] = $value;
}
}
}
I know, it seems complex but it works ;)
Upvotes: 2
Reputation: 868
If you have more than 2 words in your string, use the following code.
$values = explode(' ', $strVar);
$count = count($values);
$array = [];
for ($i = 0; $i < $count / 2; $i++) {
$in = $i * 2;
$array[$values[$in]] = $values[$in + 1];
}
var_dump($array);
The $array
holds oddly positioned word as key
and evenly positioned word $value
respectively.
Upvotes: 1
Reputation: 79004
Another single line:
parse_str(str_replace(' ', '=', $strVar), $array);
Upvotes: 0
Reputation: 1081
Single line for ya:
$arr = array(strtok($strVar, " ") => strtok(" "));
Upvotes: -2
Reputation: 202504
$pairs = explode(...);
$array = array();
foreach ($pair in $pairs)
{
$temp = explode(" ", $pair);
$array[$temp[0]] = $temp[1];
}
But it seems obvious providing you seem to know arrays and explode
. So there might be some constrains that you have not given us. You might update your question to explain.
Upvotes: 2
Reputation: 5931
Don't believe this is possible in a single operation, but this should do the trick:
list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;
Upvotes: 62
Reputation: 11830
Try this
$str = explode(" ","key value");
$arr[$str[0]] = $str[1];
Upvotes: 4
Reputation: 4446
You can loop every second string:
$how_many = count($array);
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $array[$i];
$value = $array[$i+1];
// store it here
}
Upvotes: 3
Reputation: 3118
$strVar = "key value";
list($key, $val) = explode(' ', $strVar);
$arr= array($key => $val);
Edit: My mistake, used split instead of explode but:
split() function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged
Upvotes: 4