Jelbert
Jelbert

Reputation: 57

How to delete the value inside the array in PHP

I want to delete the ['Phone'] inside my array.

i tried foreach and unset but only the first array delete the ['Phone'].

my example array below.

Array
(
    [0] => Array
        (
            [Name] => ads
            [Phone] => 32132
        )

    [1] => Array
        (
            [Name] => ads
            [Phone] => 321322
        )

    [2] => Array
        (
            [Name] => ads
            [Phone] => 3213222
        )

)

and my expected array.

Array
(
    [0] => Array
        (
            [Name] => ads
        )

    [1] => Array
        (
            [Name] => ads          
        )

    [2] => Array
        (
            [Name] => ads  
        )

)

Upvotes: 0

Views: 73

Answers (4)

Gaius T
Gaius T

Reputation: 41

Qirel's answer is faster I would imagine if you only have "name" and "phone". Another alternative that is easy on the eyes is:

foreach ($array as &$val) {
    unset($val["Phone"]);
}

Upvotes: 0

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

You can use map() function of Laravel Collection. and alter your original array however you want.

$newArray = collect($oldArray)->map(function($element) {
    return [
        'name' => $element['name'];
    ];
})->toArray();

Upvotes: 0

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_walk

array_walk($arr, function(&$v, $k){
  unset($v['Phone']);
}); 

Upvotes: 2

Qirel
Qirel

Reputation: 26460

If all you want is to fetch the names, you can just pluck those using array_column().

$array = array_column($array, "Name");

Upvotes: 2

Related Questions