Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return values of specific array key

Tags:

arrays

php

I read some question and I didn't solve my problem I was use array_column() but I am confused of this silly problem

I have an array $product

$product = array(
    0 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'description'=> 'Post your wall in your given time',
        'quantity' => '1',
        'unitPrice' => '120',
        'taxable' => 'true'
    ),
    1 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'description'=> 'Post your wall in your given time',
        'quantity' => '1',
        'unitPrice' => '120',
        'taxable' => 'true'
    ),
    2 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'description'=> 'Post your wall in your given time',
        'quantity' => '1',
        'unitPrice' => '120',
        'taxable' => 'true'
    )
);

Now I want remove two elements unitPrice and description

$customProduct = array(
    0 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'quantity' => '1',
        'taxable' => 'true'
    ),
    1 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'quantity' => '1',
        'taxable' => 'true'
    ),
    2 => array(
        'id' => '123',
        'name' => 'Facebook status robot',
        'quantity' => '1',
        'taxable' => 'true'
    )
);
like image 253
Imran Avatar asked Sep 13 '26 04:09

Imran


1 Answers

The PHP command you need is unset(array[key]), you can access individual indexes in your array by iterating over it.

The basic solution would look like the following. Please be aware that this would modify your original array. If that is not what you want assign the product array to another variable first (2nd example below):

foreach($product as &$data) {
    unset($data['unitPrice']);
    unset($data['description']);
}

var_dump($product);

would become:

$customProduct = $product;
foreach($customProduct as &$data) {
    unset($data['unitPrice']);
    unset($data['description']);
}

var_dump($customProduct);
// $product will have its original value.
like image 129
Rangad Avatar answered Sep 14 '26 18:09

Rangad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!