Search code examples
phparraysunset

unset array keys if key is string


i have array something like this

$arr  = 
    ['0' => 
        ['0' => 'zero', 
         '1' => 'test', 
         '2' =>'testphp',
         'test'=>'zero',
         'test1'=>'test',
         'test2'=>'testphp'],
    '1' => 
        ['0' => 'z', 
         '1' => 'x', 
         '2' =>'c',
         'test'=>'z',
         'test1'=>'x',
         'test2'=>'c']
        ];

and 0,1,2 is this same as test,test1,test2. I need remove keys where is string like test,test1,test2. I know the way

foreach($arr as $a){
   unset($arr['test']);
   unset($arr['test1']);
   unset($arr['test2']);
}

but it is possible find keys without specifying the exact name, because i want only number keys.


Solution

  • A solution would be:

    Assuming you know it will only have 2 layers.

     $arr  =
    ['0' =>
        ['0' => 'zero',
            '1' => 'test',
            '2' =>'testphp',
            'test'=>'zero',
            'test1'=>'test',
            'test2'=>'testphp'],
        '1' =>
            ['0' => 'z',
                '1' => 'x',
                '2' =>'c',
                'test'=>'z',
                'test1'=>'x',
                'test2'=>'c']
    ];
    
    foreach($arr as $parentKey=>$arrayItem){
        foreach($arrayItem as $key=>$subArrayItem){
            if(!is_int($key)){
                unset($arr[$parentKey][$key]);
            }
        }
    }
    var_dump($arr);
    

    Why is it though that such arrays have been generated?