Skip to content
Advertisement

PHP send an array with subarray value(s) to a function along with its key

I have a associative array(shown below). I want to send $demographics[‘customer’] to a function and access both the key and value of the array.

    function sendValues($data) {
           print_r($data);
        }
        
        $demographics = array(
                              'customer' => array('name' => 'John', 'age' => 28),
                              'offers' => array('value' => '10.00', 'expiration' => '2021-10-01')
                        );
          
        //print_r($demographics);
        sendValues($demographics['customer']);

Actual:

    Array
   (
    [name] => John
    [age] => 28
   )

Expected:

    Array
   (
    [customer] => array(
                        [name] => John
                        [age] => 28
                       )
   )

Advertisement

Answer

If you just need to send a specific part of the array to the function, you can also use array_slice(). Like with the first element like this:

sendValues(array_slice($demographics, 0, 1));

Also refer to: https://www.php.net/manual/en/function.array-slice.php

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement