Using function array_intersect_key

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zorgi
    Recognized Expert Contributor
    • Mar 2008
    • 431

    Using function array_intersect_key

    I have a question but not a problem.

    I have 2 arrays.

    Code:
    $array_1 = array("a", "b");
    $array_2 = array("a" => "x1", "b" => "x2", "c" => "x3");
    Is there php function that would return array("a" => "x1", "b" => "x2") if passed $array_1 and $array_2 or I have to write it. Looked at the manual and couldn't find it.

    Thanks
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    you don’t need a whole new function…
    Code:
    array_intersect_key($array_2, array_flip($array_1));

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      Try array_intersect _key() for this one
      array array_intersect _key ( array array1, array array2 [, array ...] )

      array_intersect _key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
      But you will need to array_flip() $array1 to make values the key. So...
      Code:
      array_intersect_key($array2,array_filp($array1);
      ..I think

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        Originally posted by code green
        …I think
        I’ve tested that, it works.

        Comment

        • zorgi
          Recognized Expert Contributor
          • Mar 2008
          • 431

          #5
          Excellent

          Thank you

          Comment

          • code green
            Recognized Expert Top Contributor
            • Mar 2007
            • 1726

            #6
            Dormilich. You pipped me by one minute. But same solution.

            Comment

            • Dormilich
              Recognized Expert Expert
              • Aug 2008
              • 8694

              #7
              it’s the obvious solution, after all.

              Comment

              Working...