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.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.
The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
The explode in PHP function accepts three parameters. One parameter is optional, and the other two are compulsory. These three parameters are as follows: delimiter: This character is the separator which specifies the point at which the string will be split.
If you want to access the key of an array in a foreach loop, you use the following syntax: foreach ($array as $key => $value) { ... } Save this answer.
Don't believe this is possible in a single operation, but this should do the trick:
list($k, $v) = explode(' ', $strVal); $result[ $k ] = $v;
$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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With