0

if i have the following array:

array(
   'var1' => 123,
   'var2' => 234,
   'var3' => 345
);

I would like to extract specific parts of this to build a new array i.e. var1 and var3.

The result i would be looking for is:

array(
   'var1' => 123,
   'var3' => 345
);

The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.

Is there a built in php function to do this?

Edit:

The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract

3
  • 2
    Under what condition are you extracting those keys? Commented Jul 10, 2013 at 22:09
  • I dont understand completely. Can you explain what you mean by the criteria? Commented Jul 10, 2013 at 22:10
  • 1
    Well, what makes you choose var1 and var2 or is it random? Does it come from another array? Why are you choosing those 2 keys is my question. Commented Jul 10, 2013 at 22:11

2 Answers 2

5
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));

So, with your edit:

$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need a built in function to do this, try this :

$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array

// For each record in your initial array
foreach ($firstArray as $key => $value)
{
    // If the key (ex : 'var1') is part of the desired keys
    if (in_array($key, $this->keysToExtract)
    {
        $finalArray[$key] = $value; // Add to the new array
    }
}

var_dump($finalArray);

Note that this is most likely the most efficient way to do this.

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.