Search code examples
phparraysunset

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;

Solution

  • 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