Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove integer index an array

Tags:

arrays

php

mysql

I am working on a website where we need to remove the index of an array where type is integer. Have you any idea or suggestion regarding. My array looks like this :

Array
(
    [0] => first
    [first] => second
    [1] => second
    [second] => second
    [2] => third
    [third] => third
    [3] => forth
    [forth] => v
    [4] => fifth
    [fifth] => fifth
)

How we can remove integer index from array.One more thing to note that we have not static array we do not know how many index is there.

Need like this :

Array
(  
    [first] => second  
    [second] => second  
    [third] => third  
    [forth] => v
    [fifth] => fifth
)
like image 249
Sonu Sindhu Avatar asked Jul 06 '13 04:07

Sonu Sindhu


3 Answers

Database Solution:

To get only the associative array from mysql database use: mysqli_fetch_assoc() instead of mysqli_fetch_array().

mysqli_fetch_array() fetches the entire array - integer indexes as well as column names as keys.

mysqli_fetch_assoc() only fetches the column names as keys. - thus getting rid of integer keys.


General Solution:

To do what you asked in general I would use:

foreach($array as $key => $value){
    if(is_numeric($key)) unset($array[$key]);
}

You can also use is_int() if you like..

like image 151
Yotam Omer Avatar answered Nov 09 '22 03:11

Yotam Omer


Another way to do this :-

$array1 = array("6566"=>"zd  xf", "2"=>2, "c"=>3, "d"=>4, "e"=>5);
$keys=array_filter(array_keys($array1), "is_numeric");
$out =array_diff_key($array1,array_flip($keys));
print_r($out);

output :

Array
(
[c] => 3

[d] => 4

[e] => 5

)
like image 24
Rajeev Ranjan Avatar answered Nov 09 '22 04:11

Rajeev Ranjan


remove the integer index value of array.

$array1=array();
$array = array(0 => first,first => second,1 => second,second => second,2 => third,third => third,3 => forth,forth => v,4 => fifth,fifth => fifth);
foreach ($array as $key=>$value){
    if(gettype($key)=='integer'){
       unset($key);
       unset($value);
   }else{
    $array1[$key]=$value;
  }
}
print_r($array1);

out put like this.

Array

( [first] => second [second] => second [third] => third [forth] => v [fifth] => fifth )

like image 28
Raman Verma Avatar answered Nov 09 '22 03:11

Raman Verma