Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2010
    Location
    Sheffield
    Posts
    824
    Thanks
    93
    Thanked 18 Times in 18 Posts

    How to compare these 2 arrays

    I have 2 arrays

    One is set up like

    PHP Code:
    [First] => Hello
    [Second] => World 
    And the second is set up like
    PHP Code:
    [First] => Message1
    [SomeKey] => Message2
    [Second] => Message3 
    Whilst I'm running a foreach loop on the second array need to check if the key in the second array matches a key in the first array. If it doesn't in the first array I'll display the key from the second array. If it does I'll display the value from the first array.

    So an example using the above data, the output needs to look like
    Hello - Message1
    SomeKey - Message2
    World - Message3

    Does this seem okay? It's what I've got so far. $InvCount is second array and $PrimWeps is first array

    PHP Code:
    $primFound false;


    foreach (
    $InvCount as $k => $v) {
        
    $dd false;
        if (!
    $primFound) {
            foreach (
    $PrimWeps as $k1 => $v1) {

                if (
    $k == $k1) {
                    echo 
    $v1 ' - ' $v "\r\n";
                    
    $primFound true;
                    
    $dd true;
                }
            }
        }
        if (!
    $dd) {
            echo 
    str_replace('_'' '$k) . ' - ' $v "\r\n";
        }

    Last edited by tomharto; 04-24-2013 at 11:37 AM.

  • #2
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,011
    Thanks
    2
    Thanked 312 Times in 304 Posts
    Code:
    $first_array['First'] = 'Hello';
    $first_array['Second'] = 'World';
    
    $second_array['First'] = 'Message1';
    $second_array['SomeKey'] = 'Message2';
    $second_array['Second'] = 'Message3';
    
    foreach($second_array as $key=>$value){
    	// lookup and replace the $key value if found in the $first_array
    	if(isset($first_array[$key])){
    		$key = $first_array[$key];
    	}
    	echo "$key - $value<br>";
    }
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • Users who have thanked CFMaBiSmAd for this post:

    tomharto (04-24-2013)

  • #3
    Regular Coder
    Join Date
    Jul 2010
    Location
    Sheffield
    Posts
    824
    Thanks
    93
    Thanked 18 Times in 18 Posts
    I knew there had a to be a better way, thanks


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •