views:

252

answers:

3

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, 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: 

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

eyazici
list() is really in the opposite direction: it takes a list of variables and an array and assigns each item in the array to the corresponding variable (i.e. it's a way to get things OUT of an array rather than a way to put things IN).
JacobM
You could do something like $info = array(4,5,6); list($a['foo'], $a['bar'], $a['baz']) = $info; but using "list" there really isn't buying you anything.
JacobM
this method works, but it's exactly what i was trying to avoid. I don't want to type the name of the assoc array for every single key. something like "assoc_array_slice( $array, 'foo','bar','baz') = array( 4, 5, 6 )" is what I'm really looking for.
spudly
Yes, but there is no 1-to-1 equivalent to the given example in PHP, I try to the closest.
eyazici
A: 

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
dnagirl
A: 

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.

Lucas Oman