Stephen
Stephen

Reputation: 2550

PHP: How to get both key and value from an associative array?

I have this associative array structure:

$multiArray = array(
                 'key1' => array(1, 2, 3, 4),                
                 'key2' => array(5, 6, 7, 8),
                 'key3' => array(9, 10, 11, 12)
              );

When I call $multiArray['key1'], I get the value (which is normal):

// Example 1
$multiArray['key1'];
//$multiArray only has [1, 2, 3, 4]

Is there a way that when I call I want $multiArray['key1'] that I can have ['key1' => array(1,2,3,4)] or the other two keys, depending on the situation?

I could structure $multiArray like so, but I was wondering if there is a better way.

// Example 2
$multiArray = array(
                 'keyA' => array('key1' => array(1, 2, 3, 4)),  
                 'keyB' => array('key2' => array(5, 6, 7, 8)),
                 'keyC' => array('key3' => array(9, 10, 11, 12))
              );
$multiArray['keyA'];
// $multiArray is now what I want: ['key1' => [1, 2, 3, 4]]

Upvotes: 0

Views: 108

Answers (2)

aust
aust

Reputation: 914

I think what you may be looking for is foreach:

$myArray = array('key1' => array(1, 2, 3), 'key2' => array(4, 5, 6));
$multiArray = array();
foreach ($myArray as $key => $value) {
    // $key would be key1 or key2
    // $value would be array(1, 2, 3) or array(4, 5, 6)
    $multiArray[] = array($key => $value);
}

Upvotes: 1

bcmcfc
bcmcfc

Reputation: 26745

You could do something like this:

function getArray ($multiArray, $key) {
    return array($key => $multiArray[$key]);
}

or

$result = array('key1' => $multiArray['key1']);

A little more context as to how you're using it would be useful though. It sounds like you already know the requested key at the point of use. If not you may need to use array_keys.

Upvotes: 1

Related Questions