I have a string - something like
$string = 'key1=value1, key2=value2, key3=value3';
How can I get an array from the given string like the following?
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
);
parse_str(str_replace(", ","&",$string),$array);
A naive solution could be :
$string = 'key1=value1, key2=value2, key3=value3';
$array = array();
foreach (explode(', ', $string) as $couple) {
list ($key, $value) = explode('=', $couple);
$array[$key] = $value;
}
var_dump($array);
And you'd get the expected array as a result :
array
'key1' => string 'value1' (length=6)
'key2' => string 'value2' (length=6)
'key3' => string 'value3' (length=6)
This is exactly what parse_str do. In your case, you need to replace your commas with a &:
$string = 'key1=value1, key2=value2, key3=value3';
$array = parse_str(str_replace(', ', '&', $string));
// Yields
array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
)
$a = explode(', ', $string);
$array = array();
foreach($a as $v){
$x = explode('=', $v);
$array[$x[0]] = $x[1];
}
Related
I have two arrays with different sizes and I want to do some action when two items are equal.
my arrays may look like this
array_1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
array_2 = { 'key2' => 'value2' }
in the example above I want to perform an action when key2 from array_1 and key2 from array_2 are found.
Currently I am using 2 foreach loops to do this. Something like this:
foreach ($block->getSettingsNoDefaults() as $baseKey => $value) {
$found = false;
foreach ($blockData->settings as $saveKey => $value) {
if($baseKey == $saveKey) {
$found = true;
break;
}
}
if(!$found) {
$block->removeSetting($baseKey);
}
}
Is there a way to use some other more elegant way to do this insead of two foreach loops to compare all values from one array to all values from second array and then act if they match?
I thought first of using php's array_map("myfunction",$array_1 ,$array_2) to do this but it does not seem like right function in my case, since it will loop through both arrays and only compare elements that are at the same index.
Is there any other function that I can use in my case so I can make my code more elagant then using multiple forloops.
You can use array_key_exists and one foreach loop.
Solution
$array_1 = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' ];
$array_2 = [ 'key2' => 'value2' ];
foreach($array_2 as $key => $item){
if(array_key_exists($key, $array_1)){
echo "Match found.";
}
}
Updated Answer I found that you can use array_intersect_key($a1,$a2) instead
$array_1 = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');
$array_2 = array('key2' => 'value2' );
$result = array_intersect_key($array_1,$array_2);
print_r($result);
Please read the whole question before attempting to answer. If I have two associative arrays where some values match just once:
$array1 = ['key1' => 'value1', 'key3' => 'value2', etc...];
$array2 = ['key2' => 'value1', 'key4' => 'value2', etc...];
but $array2 is longer than $array 1, and in those cases the keys don't have values:
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
Then how can I combine them to get the following result:
$array3 = [
'value1' => [$myconstant => key2],
'value2' => [$myconstant => key4],
'value3' => [$myconstant => ''],
etc...];
Notice that in cases where there is no match, an empty string is used instead of the key in the embedded associative array. In fact, the only reason why $array1 is necessary is because I need to know when there is a match with $array2 to get the correct format.
The values will not repeat themselves along the etc... chain.
I'm using Laravel and am trying to use Collections, but basic PHP solutions are okay too. Thank you very much.
I guess the biggest hurdle you have is how to transform those values in keys and keys into values. array_flip is the answer to that problem. Once you have that, you can solve your problem with a simple foreach loop.
$myconstant = 'foo';
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
// array_flip switches keys and values in an array
$flip1 = array_flip($array1);
$flip2 = array_flip($array2);
$array3 = [];
foreach($flip2 as $key => $value) {
if(!isset($flip1[$key])) {
$array3[ $key ] = [ $myconstant => '' ];
} else {
$array3[ $key ] = [ $myconstant => $value ];
}
}
Laravel Collections have a flip() method, too. That might help you translating the script into Laravel.
<?php
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
function x (array $a= array(), array $b = array()) {
$array = array();
$index = new ArrayObject($a);
$seed = new ArrayObject($b);
$a_it = $index->getIterator();
$b_it = $seed->getIterator();
while ($a_it->valid()) {
$x = $a_it->current();
$y = ($b_it->valid()) ? $b_it->current() : NULL;
if ($y !== NULL) {
# there is a value to compare against
if ($x === $y) {
$array["{$x}"] = array('myConst'=>$a_it->key());
}
$b_it->next();
} else {
# there is no value to compare against
$array["{$x}"] = array('myConst'=> '');
}
$a_it->next();
}
return $array;
}
$read = x($array2, $array1);
print_r($read);
I have an result array like this:-
$array = array(
'key1' => array('...'),
'key2' => array('...'),
'key3' => array('...'),
'key4' => array('...'),
.
.
.
.
'keyn' => array('...')
);
I need to get 5 elements from above array. first time key1 to key5, key6 to key10
and so on...... On the basis of condition I need to perform operation on this.
I need output :-
$array = array(
'key1' => array('...'),
'key2' => array('...'),
'key3' => array('...'),
'key4' => array('...'),
'key5' => array('...')
);
I can get value if my key value directly $array['key1']....$array['key5'] but if key is unknown value than
I am facing problem.
Thanks in advance.
To iterate over such an array you can use array_slice() in this manner:
$n = count($array);
$len = 5;
for ($i = 0; $i + $len <= $n; $i += $len) {
$chunk = array_slice($array, $i, $len, true);
// do work on $chunk
}
you can just splice or slice the first 5 items off of the array.
<?php
$array = array(
'key1' => array('...'),
'key2' => array('...'),
'key3' => array('...'),
'key4' => array('...'),
'key5' => array('...'),
'key6' => array('...'),
'key7' => array('...')
);
$arraySlice1 = array_slice($array, 0, 5);
$arraySlice2 = array_splice($array, 0, 5);
Slice will leave $array intact and $array will still hold 7 items, splice will remove the returned results from $array, so $array will only hold key6 and key7
Edit: A better way is array_slice. See this question. Example:
$fifthElement = array_slice($array,4,1); //will get the 5th element
You can use foreach in a way that gives you the keys and the associated values. So, to get the fifth key-value-pair, you could write:
$i = 1;
foreach($array as $key => $value)
{
if($i == 5)
{
echo "Fifth Key=".$key." value=".$value."\n";
}
$i++;
}
array_slice surely works for you
$first_five_elements = array_slice($array, 0, 5);
Here is codepad
Say I have the following code:
$arr = array('id' => $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam'));
echo '' . implode( ', ', $tarr) . '';
This displays: Fred, Wilma, Bam Bam
but the href shows value Array instead of Fred for Fred, Wilma for Wilma etc
Cheers
You can build an output string (or array as shown here) using a foreach loop:
foreach($tarr as $v){
$out[] = "<a href='?tag=$v'>$v</a>";
}
echo implode(', ', $out)
I think what youy are trying to do is this:
$arr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam');
echo '';
$tarr is an array, so when it's converted to a string, it prints Array.
Don't use implode here, you should use a for loop to get each value of the array.
What you should do is something like this:
$tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam');
$aTags = array();
foreach($tarr as $v){
$aTags[] = ''.$v.'';
}
echo implode(', ', $aTags);
Also, why do you have $arr here? It's totally useless.
$arr = array('id' => $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam'));
This is the same as:
$tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam');
$arr = array('id' => $tarr);
I have an array:
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'key4' => 'value4',
'key5' => 'value5',
);
and I would like to get a part of it with specified keys - for example key2, key4, key5.
Expected result:
$result = array(
'key2' => 'value2',
'key4' => 'value4',
'key5' => 'value5',
);
What is the fastest way to do it ?
You need array_intersect_key function:
$result = array_intersect_key($array, array('key2'=>1, 'key4'=>1, 'key5'=>1));
Also array_flip can help if your keys are in array as values:
$result = array_intersect_key(
$array,
array_flip(array('key2', 'key4', 'key5'))
);
You can use array_intersect_key and array_fill_keys to do so:
$keys = array('key2', 'key4', 'key5');
$result = array_intersect_key($array, array_fill_keys($keys, null));
array_flip instead of array_fill_keys will also work:
$keys = array('key2', 'key4', 'key5');
$result = array_intersect_key($array, array_flip($keys));
Only way I see is to iterate the array and construct a new one.
Either walk the array with array_walk and construct the new one or construct a matching array and use array_intersect_key et al.