user6384346
user6384346

Reputation:

how do i unset multiple keys in php

I am getting error while unset the data. Can anyone tell me how to do that. Here i have column array look like:-

enter code here
Array
(
[0] => Id
[1] => Name
[2] => MainDeity
[3] => Description
[4] => MainImage
[5] => Category
[6] => Tehsil
[7] => City
[8] => District
[9] => State
[10] => Terrain

) I am using laravel framework i want to unset three columns Id,State,Terrain I have used this code but it shows me error:- Cannot unset string offsets

enter code here
 $columns = Schema::getColumnListing('places');
    foreach ($columns as $key => $value) {
        if($value=="Id"){
            unset($value[$key]);
        }
        $columndata[] = $value;
    }

    echo "<pre>";print_r($columndata); die;

Upvotes: 3

Views: 7276

Answers (3)

Peter
Peter

Reputation: 2181

This is an easy one-liner:

$result = array_diff(Schema::getColumnListing('places'), ['Id', 'State', 'Terrain']);

Upvotes: 3

Rahul
Rahul

Reputation: 18557

Check this code,

$arr = ["0" => "Id", "1" => "Name"
    ];
    $columndata = [];
 foreach ($arr as $key => &$value) {
    if(in_array($value,["Id",'State','Terrain']){
        unset($value);
    }else{
     $columndata[] = $value;
    }
}
$columndata = array_values(array_filter($columndata));
print_r($columndata);

Error was coming because, after check id, you are unsetting that value. And then trying to save that value in columndata.

Here is working code

Upvotes: 0

Naga
Naga

Reputation: 2168

Should be like this,

 $columns = Schema::getColumnListing('places');
    foreach ($columns as $key => $value) {

        if($value=="Id"){
            unset($columns[$key]);
        } else {
            $columndata[] = $value;
        }   

    }

    echo "<pre>";print_r($columndata); die;

Upvotes: 0

Related Questions