15Answers
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;
  • 47
Reply Report
      • 1
    • Thanks, this way has more efficient mem use. TIP: When foreach is using this recursive making a large array, you can unset() the original/source array after $result is populated. This will trim memory. Ie, when parsing Google shopping categories from their [crappy] txt file a temp array is created using file() then explode() on each row string to isolate an ID as the key. The source array has 5425 rows containing strings. That array is ~1mb, and its temporary, nuke it :)
$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
            )
  • 9
Reply Report
$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

  • 4
Reply Report

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
}
  • 3
Reply Report
$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.

  • 2
Reply Report

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

  • 2
Reply Report

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.

  • 1
Reply Report

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',
]
  • 0
Reply Report

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
)
  • 0
Reply Report

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

  • 0
Reply Report

Single line for ya:

$arr = array(strtok($strVar, " ") => strtok(" "));
  • -1
Reply Report
    • Not my downvote, but this is a code-only answer and these types of answers do very little to educate future readers. If you want to earn rep points, please improve your answer to include an explanation as to why this is an appropriate method and how it works. (I know how it works BTW)

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions