5

I have a function that returns an array where the value is an array like below: I want to ignore the key and extract the value directly. How can I do this without a for loop? The returned function only has one key but the key (2 in this case) can be a variable

Array ( [2] => Array ( [productID] => 1 [offerid]=>1)

Expected result:

Array  ( [productID] => 1 [offerid]=>1)
0

3 Answers 3

3

There're at least 3 ways of doing this:

Use current function, but be sure that array pointer is in the beginning of your array:

$array = Array (2 => Array ( 'productID' => 1, 'offerid' => 1));
$cur = current($array);
var_dump($cur, $cur['offerid']);

Next is array_values function, which will give you array of values with numeric keys, starting with 0

$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$av = array_values($array);
var_dump($av[0], $av[0]['offerid']);

And third option is use array_shift, this function will return first element of array, but be careful as it reduces the original array:

$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to get the current value of an array, you can use current() assuming the array pointer is in the correct position. If there is only one value, then this should work fine.

http://php.net/manual/en/function.current.php

Comments

0

I think Devon's answer will work for you , but if not your can try

$arr = array_column($arr, $arr[2]);

if you need always the second index of your master array, if you need all index use

array_map(),

something like array_map('array_map', $arr); should work.

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.