Home » Php » php – explode() into $key=>$value pair

php – explode() into $key=>$value pair

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&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;

Answer:

$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
            )

Answer:

$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

Answer:

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
}

Answer:

Try this

$str = explode(" ","key value");
$arr[$str[0]] = $str[1];

Answer:

$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.

Answer:

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 😉

Answer:

Another single line:

parse_str(str_replace(' ', '=', $strVar), $array);

Answer:

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.

Answer:

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',
]

Answer:

list($array["min"], $array["max"]) = explode(" ", "key value");

Answer:

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
)

Answer:

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

Answer:

Single line for ya:

$arr = array(strtok($strVar, " ") => strtok(" "));

Answer:

I found another easy way to do that:

$a = array_flip(explode(' ', $strVal));