hmamun
hmamun

Reputation: 154

using foreach loop to delete last element from associative array

I want to delete price index from each of the array.

Here is a sample code:

Array([0] => Array
    (
        [player_id] => 108
        [trnmnt_team_id] => 1
        [player_type] => 1
        [user_team_id] => 11
        [user_id] => 4
        [price] => 10.00
    )
[1] => Array
    (
        [player_id] => 151
        [trnmnt_team_id] => 2
        [player_type] => 1
        [user_team_id] => 11
        [user_id] => 4
        [price] => 10.00
    )
)

I tried to delete following way but it shown unexpected 'unset' (T_UNSET):

foreach ($mergeAllType as $key => $value) {
    $price=$value;
    $withOutPrice[]=unset($price['price']);
}

Upvotes: 0

Views: 658

Answers (4)

Mikey
Mikey

Reputation: 2704

If you want to unset() all off the price keys in your array you can use array_walk()

array_walk($arr, function(&$array) {
    unset($array['price']);
});

Just replace $arr with whatever your arrays name is, i.e. $teams.

If you want to have two arrays, one with price and one without price you could duplicate the array before doing the above; i.e.

$teams = <DATASOURCE>
$teamsWithoutPrice = $teams;

array_walk($teamsWithoutPrice, function(&$array) {
    unset($array['price']);
});

Then if you print out your $teamsWithoutPrice array you'll have your array with the price key removed.

Hope it helps.

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

You already got your answers regarding your foreach loop.
So, let me give you a different answer, using array_map and an anonymous function ;-)

<?php
$src = array(
    array (
        'player_id' => 108,
        'trnmnt_team_id' => 1,
        'player_type' => 1,
        'user_team_id' => 11,
        'user_id' => 4,
        'price' => 10.00,
    ),
    array (
        'player_id' => 151,
        'trnmnt_team_id' => 2,
        'player_type' => 1,
        'user_team_id' => 11,
        'user_id' => 4,
        'price' => 10.00,
    ),
);

$withOutPrice = array_map(
    function($e) {
        unset($e['price']);
        return $e;
    },
    $src
);

var_export($withOutPrice);

Upvotes: 0

Max
Max

Reputation: 2524

Tomas.lang's answer works fine if you know the last index's key. However if you don't know the name of the last key you could use the following:

unset(end($price));
$withOutPrice = $price;

Upvotes: 1

tomas.lang
tomas.lang

Reputation: 499

unset doesn't returns any value (it's language construct, not a function), you must do it following way:

unset($price['price']);
$withOutPrice[] = $price;

Upvotes: 1

Related Questions