Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explode() into $key=>$value pair

Tags:

php

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.

like image 629
Borniet Avatar asked Apr 12 '13 08:04

Borniet


People also ask

What does the explode () function do?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.

What does the explode () function return?

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.

How many parameters does explode () function have?

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.

How do you enter a value in an array with a key?

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.


2 Answers

Don't believe this is possible in a single operation, but this should do the trick:

list($k, $v) = explode(' ', $strVal); $result[ $k ] = $v; 
like image 166
smassey Avatar answered Oct 03 '22 14:10

smassey


$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             ) 
like image 32
Alienoiduk Avatar answered Oct 03 '22 16:10

Alienoiduk