skip to Main Content

I have a multi diemntional array as follow:

Array
(
    [0] => transactionType:"for_rent"
    [1] => perPage:15
    [4] => page:1
    [6] => exclusive:true
    [options] => Array
        (
            [0] => has_parking
            [1] => has_climate_control
            [2] => has_pool
        )

)

I want to extract options array into a separate variable $options and leave remaining array without options subarray like:

Array
(
    [0] => transactionType:"for_rent"
    [1] => perPage:15
    [4] => page:1
    [6] => exclusive:true
)

There must be such php function or an easy way but I can’t figure it out.

I tried extract function also array_slice but can’t figure out.

2

Answers


  1. You can simply copy the subarray and unset it from the main array:

    $mainArray = [
    
        'transactionType:"for_rent"',
        'perPage:15',
        'page:1',
        'exclusive:true',
    
        'options' => [
    
            'has_parking',
            'has_climate_control',
            'has_pool'
        ]
    
    ];
    
    $options = $mainArray['options'];
    unset ($mainArray['options']);
    
    // print_r ($options);
    // print_r ($mainArray);
    
    Login or Signup to reply.
  2. As Pippo mentioned you can use unset() function but if options array is always latest
    you can also use array_pop() function (detailed: https://www.php.net/manual/en/function.array-pop.php)
    example:

    $array = ["transactionType" => "for_rent", "perPage" => 15, "page" => 1, "options" => ["has_parking", "has_climate_control", "has_pool"]]; 
    $options = array_pop($array);
    print_r($array);
    print_r($options);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search