Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Ignore key and extract value of an array

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)
like image 700
FBP Avatar asked Sep 26 '22 20:09

FBP


1 Answers

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']);
like image 66
u_mulder Avatar answered Sep 28 '22 23:09

u_mulder