assigning to an associative array slice in php
In perl, I could assign a list to multiple values in a hash, like so:
# define the hash...
my %hash = (
foo => 1,
bar => 2,
baz => 3,
);
# change foo, bar开发者_JS百科, and baz to 4, 5, and 6 respectively
@hash{ 'foo', 'bar', 'baz' } = ( 4, 5, 6 );
Is there any way to do the same in php? In fact, is there even a way to get a slice of an assoc array at all?
A simple one-liner (some of these methods require newer versions of PHP than were available at the time of asking):
$hash = array(
'foo'=>1,
'bar'=>2,
'baz'=>3,
);
$hash = array_merge( $hash, array( 'foo' => 4, 'bar' => 4, 'baz' => 5 ) );
PHP Manual entry for array_merge.
If you're looking to GET a set of specific array keys, you can use this:
$subset = array_intersect_key( $hash, array_fill_keys( array( 'foo', 'baz' ), '' ) );
PHP Manual entries for array_intersect_key and array_fill_keys.
Define the hash:
$hash = array(
'foo' => 1,
'bar' => 2,
'baz' => 3,
);
# change foo, bar, and baz to 4, 5, and 6 respectively
list($hash['foo'], $hash['bar'], $hash['baz']) = array( 4, 5, 6 );
# or change one by one
$hash['foo'] = 1;
$hash['bar'] = 2;
$hash['baz'] = 3;
See the list() function in manual:
http://php.net/manual/en/function.list.php
There is no equivalent to the Perl syntax. But you can make an array of the keys of interest and use that to change only part of your array.
$koi=array('foo', 'bar', 'baz' );
foreach($koi as $k){
$myarr[$k]++; //or whatever
}
or
array_walk($myarr, create_function('&$v,$k','$v=(in_array($k,$koi))? $v*2 : $v;')); //you'd have to define $koi inside the function
In short, no. However, you could use a function like this:
function assignSlice($ar,$keys,$args) {
if (count($keys) !== count($args)) {
// may want to handle more gracefully;
// simply returns original if numbers of keys and values
// don't match
return $ar;
}
foreach ($keys as $index=>$key) {
$ar[$key] = $args[$index];
}
return $ar;
}
$test = array(
'foo'=>1,
'bar'=>2,
'baz'=>3,
);
$newtest = assignSlice($test,array('foo','bar'),array(4,5));
Edit: adjusted code in response OP's comment on question.
精彩评论