# [SOLVED] PHP: how to replace values of an array with values from 2nd array



## esso82 (Oct 6, 2009)

hi

I'm a bit unexperienced in this, so I need some help

I have two arrays:
$users
Array ( [1] => esso82 [4] => semkovic [8] => krtko2121 )

and
$msg
Array ( [0] => 1 [1] => 4 [2] => 8 [3] => 1 )

what do I need to do, is go through the second array and replace its values by values from first array where value of second array is a key of first array
do you understand me?

say we don't need to replace those values, we can make another array, but it should end up like this: ie 
$output
Array ( [0] => esso82 [1] => semkovic [2] => krtko2121 [3] => esso82 )


thanks for any help, as my logic is nort working at the moment


----------



## Nicitel (Nov 8, 2009)

*Re: PHP: how to replace values of an array with values from 2nd array*

Hello, if you still need help, try this :smile:


```
<?php
$users = array( 1 => 'esso82', 4 => 'semkovic', 8 => 'krtko2121' );
$msg = array( 0 => 1, 1 => 4, 2 => 8, 3 => 1 );


$output = array();

foreach ( $msg as $msg_id => $user_id )
{
     if ( ! isset($users[$user_id]) ) { continue; } //skip, if user_id doesn't exists

     $output[$msg_id] = $users[$user_id];
}

print_r($output);
//$output is: Array ( [0] => esso82 [1] => semkovic [2] => krtko2121 [3] => esso82 ) 

?>
```
I suppose that the array _$users_ contains "key => value" pair in shape "user_id => user_name" and array _$msg_ "msg_id => user_id".

That thing above will create a new array _$output_, with keys from _$msg_ and values from _$users_ using "user_id" from _$msg_.

It has one check. If in _$msg_ will be some "user_id" that is not in _$users_, it will try to add a value that doesn't exists and thus creating a *Notice*, and that's bad. So it will rather skip that bad iteration. :upset:

I hope that helped, and sorry for my bad English, maybe I could use google translate with better effect next time :laugh: :wave:


----------



## esso82 (Oct 6, 2009)

*Re: PHP: how to replace values of an array with values from 2nd array*

hi buddy, thanks for your post, but I fergot to update, I already sorted this out the same way ... my logics started to work again  ... but thanks once again


----------



## ahmorrow (May 5, 2009)

*Re: PHP: how to replace values of an array with values from 2nd array*

Please mark this post as solved.

Go up to the original post and under "Thread Tools" you'll find "Mark as Solved" or something similar.


----------

