I have this:
$strVar = \"key value\";
And I want to get it in this:
array(\'key\'=>\'value\')
I tried
$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
Try this
$str = explode(" ","key value");
$arr[$str[0]] = $str[1];
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.
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
}
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 ;)
Single line for ya:
$arr = array(strtok($strVar, " ") => strtok(" "));