1

I have a variable which containts comma separated values like this: $str = "1,5";

To convert it to array I have the following code:

$str = "1,5";
$replacements = explode(',', $str);

Now the array looks like following:

Array
(
  [0] => 1
  [1] => 5
)

I have this another array: $base = array('1'=>'Bread','5'=>'Butter');

What I am trying to do is replace the values of the numeric array with the value of associative array above based on the key of the associative array and the value of the numeric array and it should look like following:

// This is what I am trying to achive
Array
(
  [0] => Bread  // because 1 = Bread in the assoc. array
  [1] => Butter // because 5 = Butter in  the assoc. array
)

To achive this ,I tried the following code:

$str = "1,5";
$replacements = explode(',', $str);         
$base = array('1'=>'Bread','5'=>'Butter');          
$basket = array_replace($base, $replacements);      
print_r($basket);

But it is giving me the following output:

 Array
(
[1] => 5
[5] => Butter
[0] => 1
) 

Could you please tell me how to solve this problem ?

1
  • So you want $base sorted by $replacements?
    – Orangepill
    Jun 12, 2013 at 20:02

5 Answers 5

6
$str = "1,5";
$replacements = explode(',', $str);         
$base = array('1'=>'Bread','5'=>'Butter');   
$basket = array();

foreach($replacements as $value) {
    $basket[]=$base[$value];
}
5
  • I downvoted the answer, because of the reason the PHP function is there to do this, see @Brad Christie answer. Also it is not complety safe
    – MKroeders
    Jun 12, 2013 at 20:08
  • @Hendriq I like doing it this way because it allows for fine control say that you have two different arrays and need to combine say first name and last name together into full name. i know that is not the situation here, but it allows for easy modification like that.
    – amaster
    Jun 12, 2013 at 20:12
  • 1
    @Hendriq: How is it not "safe"? Also, what if $str was "5,1"?
    – gen_Eric
    Jun 12, 2013 at 20:14
  • @Seth McClaine Thanks for your answer. It works perfectly and even if the value of $str is "5,1"; I have tried with more values in $str and changed the order and it still worked :) Thanks a lot
    – black_belt
    Jun 12, 2013 at 20:43
  • @black_belt: if the order is what you're after, just $replacements = explode(','$str); sort($replacements);? Jun 12, 2013 at 20:50
4

array_replace compares the keys of the two arrays, not the values to the keys.

Try array_map.

$basket = array_map(function($a) use($base){
    return $base[$a];
}, $replacements);

DEMO: http://ideone.com/xPhoZP

2
  • I do love this solution, even though it relies on PHP >= 5.3. ;p Jun 12, 2013 at 20:30
  • 1
    @BradChristie: I hope no one is using 5.2 or less :-P
    – gen_Eric
    Jun 12, 2013 at 20:34
4

Have a look at array_combine. This method allows you to use one array as the keys and another as the values. then you can use array_values($base) to only grab the values portion and combine from there.

Okay, after a couple sips of coffee, here ya go using built-in methods:

  • array_intersect_keys Pulls matches from one array based on key matches from another.
  • array_fill_keys convert your $replacements array in to array(1=>0,5=>0) so we can use it in array_intersect_keys.

Code:

$str = "1,5";

$replacements = explode(',', $str);
$base = array(
  1 => 'Bread',
  2 => 'Gravy',
  3 => 'Stuffing',
  4 => 'Turkey',
  5 => 'Butter',
  6 => 'Squash'
);

var_dump(array_intersect_key($base, array_fill_keys($replacements,0)));

result:

array(2) {
  [1]=>
  string(5) "Bread"
  [5]=>
  string(6) "Butter"
}

Example

and as @nickb pointed out in a comment, if you want the keys to be [0],[1] just call array_values on the result. Also, if order is important, maybe call an sort on $replacements before getting in to the fetching.

6
  • Nice use of the PHP functiones them self
    – MKroeders
    Jun 12, 2013 at 20:04
  • What if $str was "5,1"?
    – gen_Eric
    Jun 12, 2013 at 20:13
  • array_intersect_key() you say?! Brilliant! :P The only downside here is the keys don't match the OP's output, you'd need an array_values() call, but who knows, OP might not need the keys to be reset.
    – nickb
    Jun 12, 2013 at 20:24
  • @nickb: It's funny; I probably took too long to get there, but if it's any consolation I didn't see your post until just now. haha. though a HUGE benefactor was (in)sufficient coffee consumption. Jun 12, 2013 at 20:26
  • @nickb: I also took the long way and used array_fill over flip. You're right about keys, but oh well at this point. I'm calling it quits for the day as clearly my fingers and/or mind have had enough. The good news? If you asked me to do this in C# with LINQ I'd have no problem; I'm in that stuff all the time these days. ;p Jun 12, 2013 at 20:28
2

If you array_flip() the array you explode()'d, you can get some interesting results:

$flipped = array_flip( explode(',', $str));

Result:

Array 
( 
    [1] => 0 
    [5] => 1 
) 

Now, you can intersect your $base array and the $flipped array on keys with array_intersect_key():

$intersection = array_intersect_key( $base, $flipped);

Result:

Array 
( 
    [1] => Bread 
    [5] => Butter 
)

Then, just reset the indexes with array_values(): (may or may not be necessary, if you don't care about the indexes, then omit this step)

$replacements = array_values( $intersection);

Or, in a single line:

$str = "1,5";
$base = array('1'=>'Bread','5'=>'Butter');
$replacements = array_values( array_intersect_key( $base, array_flip( explode(',', $str))));

This prints:

Array 
( 
    [0] => Bread 
    [1] => Butter 
)
5
  • 1
    array_filp? Very clever! +1
    – gen_Eric
    Jun 12, 2013 at 20:18
  • thanks for your answer. if $str = "5,1"; it doesn't provide proper order.
    – black_belt
    Jun 12, 2013 at 20:39
  • @black_belt - If that order was important, it's a very important detail you omitted from your question :) My solution is using the ordering within $base as a priority, if your desire is to have the ordering of $str, then changes can be made.
    – nickb
    Jun 12, 2013 at 20:56
  • @nickb . Thanks for your reply. I think I made it clear in my question :) by this >" What I am trying to do is replace the values of the numeric array with the value of associative array above based on the key of the associative array and the value of the numeric array and it should look like following" :)
    – black_belt
    Jun 12, 2013 at 21:04
  • @black_belt - My answer fulfils those requirements, and mimics your example output. However, your original post fails to mention that the order within the $str must be preserved.
    – nickb
    Jun 22, 2013 at 23:52
1

Try this:

$basket=array();
foreach($replacements as $value) {
   array_push($basket, $base[$value]);
}
print_r($basket);

Hopefully it works.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.