1

I have an array $minus

array(3) { [0]=> string(6) "people" 
           [1]=> string(7) "friends" 
           [2]=> string(8) "siblings" 
         }

And I have an array $user

array(3) { ["people"]=> string(3) "100" 
           ["friends"]=> string(2) "10" 
           ["siblings"]=> string(2) "57" 
         }

I can get the values of $user by using the values of $minus like,

echo $user[$minus[0]] . ', ' . $user[$minus[1]] . ', ' . $user[$minus[2]];
// Would echo: 100, 10, 57

But how can I get the values of $user by using the values of $minus into a new array, the new array should be like,

array(3) { [0]=> string(3) "100" 
           [1]=> string(2) "10" 
           [2]=> string(2) "57" 
         }

I have tried using foreach loops but can never get it right?

0

5 Answers 5

4
foreach($minus as $key=>$value) {
  $new_array[$key] = $user[$value];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Worked brilliantly, thank you for this. Is there any good links for documentation on this?
The PHP documentation is always brilliant - php.net/manual/en/control-structures.foreach.php.
It is better to initialize the array before the foreach. $new_array= array();
You agree but I am unvotted :P Just kidding
3

Use array_map, PHP >= 5.3 only

$new_array = array_map(function($item) use ($user) {return $user[$item];}, $minus);

3 Comments

@novactown.com what's your PHP version?
Thanks for this, in terms of speed would this be better or a for each loop? I am guessing this as it doesn't need to iterate through the items or does it?
@novactown.com It should be faster, but you should probably benchmark the two. Also, if you use this in several places, you might wanna make it a named function instead of an anonymous one, as I'm not sure how the interpreter optimizes it.
1
$new_array= array();
foreach ($minus as $key => $value){
 $new_array[$key] =  $user[$value];
    }
print_r($new_array);

Comments

0
$new_array = array($user[$minus[0]], $user[$minus[1]], $user[$minus[2]]);

1 Comment

I didn't downvote, but it's not the best solution - it only works as long as the keys have that name, and there are exactly 3 members of the array. If the key names or the size of the array change, this will have to be changed.
0
$minus = array(0 => "people",
               1 => "friends",
               2 => "siblings"
              );

$user = array("people"   => "100",
              "friends"  => "10",
              "siblings" => "57"
             );


$newArray = $minus;
array_walk($newArray,function(&$item, $key, $prefix) { $item = $prefix[$item]; },$user);

var_dump($newArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.