0

So I came to a point where I need to check a value inside an array:

Array [
    'oneName' => [
        'val'   => 'str',
        'price' => 'int'
    ],
    'twoName' => [
        'val'   => 'str',
        'price' => 'int'
    ]
]

however, these oneName, twoName key names are dynamically created from another script. I need to check the value of twoName['price'] (for example) in an if statement which is fine. I came across this SO post regarding a similar topic: php - get numeric index of associative array but this is done by specifying the key name and returning the index value based on that. How can I access twoName via a numeric index without specifying the key name? Or am I asking the impossible?

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • 2
    You may use `array_values($your_arr)` before access it through numeric values.. – Murad Hasan Jun 29 '17 at 09:26
  • @FrayneKonok will this work for multi-dimensional arrays too? :) – treyBake Jun 29 '17 at 09:30
  • For your array this will works and output will be like: `Array ( [0] => Array ( [val] => str [price] => int ) [1] => Array ( [val] => str [price] => int ) )` – Murad Hasan Jun 29 '17 at 09:31
  • 1
    @FrayneKonok awesome, I just looked at the PHP documentation for the function and yeah looks like it's ok, not to fussed about order of array - if you turn it into an answer, I'd be happy to accept / upvote – treyBake Jun 29 '17 at 09:32
  • To downvoter - I'm ok with it, but please leave an explanation so I can improve. A downvote without explanation is just as bad as a bad question - no one learns – treyBake Jun 29 '17 at 09:34

1 Answers1

2

To get numeric index of associative array without specifying the key name you need to use the array_values() function.

Example:

$arr = [
    'oneName' => [
        'val'   => 'str',
        'price' => 'int'
    ],
    'twoName' => [
        'val'   => 'str',
        'price' => 'int'
    ]
];

$arr = array_values($arr);
print_r($arr);

Output:

Array
(
    [0] => Array
        (
            [val] => str
            [price] => int
        )

    [1] => Array
        (
            [val] => str
            [price] => int
        )

)
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42