PHP: ignore key and retrieve array value

I have a function that returns an array, where the value is an array, as shown below: I want to ignore the key and retrieve the value directly. How can I do this without a for loop? The returned function has only 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)
+4
source share
3 answers

There are at least 3 ways to do this:

Use a function current, but make sure the array pointer is at the beginning of your array:

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

The next function array_values, which will give you an array of values ​​with numeric keys, starting with0

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

- array_shift, , , :

$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);
+3
+1

I think Devon's answer will work for you, but if you cannot try

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

if you always need the second index of your main array, if you need the whole index

array_map(),

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

0
source

Source: https://habr.com/ru/post/1621391/


All Articles