explode() into $key=$value pair
Don't believe this is possible in a single operation, but this should do the trick:
list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;
Split string with only one delimiting character into key-value pairs
Try this
$string = "Part1:Part2:Part3:Part4";
$arr = explode(":", $string);
$key = "";
$i = 0;
$newArray = [];
foreach($arr as $row){
if($i == 0){
$key = $row;
$i++;
} else {
$newArray[$key] = $row;
$i = 0;
}
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
split string into key value pair
You could split the string by looking if not a comma follows and a colon.
var string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist, foo: bar, bar, bar";
console.log(string.split(/, (?=[^,]+:)/).map(s => s.split(': ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Split string into key-value pairs
You could do a single call to split() and a single pass on the String using the following code. But it of course assumes the String is valid in the first place:
Map<String, String> map = new HashMap<String, String>();
String test = "pet:cat::car:honda::location:Japan::food:sushi";
// split on ':' and on '::'
String[] parts = test.split("::?");
for (int i = 0; i < parts.length; i += 2) {
map.put(parts[i], parts[i + 1]);
}
for (String s : map.keySet()) {
System.out.println(s + " is " + map.get(s));
}
The above is probably a little bit more efficient than your solution, but if you find your code clearer, then keep it, because there is almost zero chance such an optimization has a significant impact on performance, unless you do that millions of times. Anyway, if it's so important, then you should measure and compare.
EDIT:
for those who wonder what ::?
means in the above code: String.split() takes a regular expression as argument. A separator is a substring that matches the regular expression. ::?
is a regular expression which means: 1 colon, followed by 0 or 1 colon. It thus allows considering ::
and :
as separators.
php split a file into $key=$value pairs with duplicate keys
I think your problem is you override the value for your key.
$returnArray[$key] = $value;
so what yo want is to append your values to a subarray with the $key
as the parent.
$returnArray[$key][] = $value;
With the []
you append the $value
to the underlying array.
How to implode array with key and value without foreach in PHP
and another way:
$input = array(
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n'
);
$output = implode(', ', array_map(
function ($v, $k) {
if(is_array($v)){
return $k.'[]='.implode('&'.$k.'[]=', $v);
}else{
return $k.'='.$v;
}
},
$input,
array_keys($input)
));
or:
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
How to push both value and key into PHP array
Nope, there is no array_push()
equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
PHP - split String in Key/Value pairs
If you don't mind using regex ...
$str = "key=value, key2=value2";
preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r);
$result = array_combine($r[1], $r[2]);
var_dump($result);
Related Topics
Woocommerce Custom Checkout Field to Add Fee to Order Ajax
Warning: Preg_Replace(): Unknown Modifier 'G'
Laravel Escaping All HTML in Blade Template
PHP Post_Max_Size VS Upload_Max_Filesize, What Is the Difference
PHP Preg_Match (.*) Not Matching Past Line Breaks
Show/Hide Fields Depending on Select Value
Get Variable from PHP File Using Jquery/Ajax
Executing a Powershell Script from PHP
Downloading a File with a Different Name to the Stored Name
How to Display Xml in HTML in PHP
How to Explain the Result for a New \Datetime('0000-00-00 00:00:00')
Scale Image Using PHP and Maintaining Aspect Ratio
How to Notify a User After an Access_Control Rule Redirects
Compile Error: Cannot Use Isset() on the Result of an Expression