Вопрос

How can I tell if array element, in foreach loop, has a key?

Some code:

function test($p_arr){
   foreach ($p_arr as $key => $value){
     // detect here if key 'came with the array' or not
   }
}

$arr1['a'] = 10;
$arr2[] = 10;
$arr3[2] = 10;

test($arr1); // yes
test($arr2); // no
test($arr3); // yes

edit #1


I am aware that $arr2 also as an automated index-key. I need to know if it is automated or not.

edit #2


My use of it is simple.
In the function, I create a new array and use the $key as the new $key, if it was provided by the function call. or the $value as the new $key, if it was omitted in the function call.

I know that I can just force the use of key to each element, but in some parts of the code, the data structure itself is very dynamic* - and i'm trying to stay flexible as much as possible.

*code that create other code, that create ... and so on.

Это было полезно?

Решение 3

Every array created has to have a key, whether it's a integer or string as the key or index, without no index the PHP would have no way to interpret or even pull information from the array it's self.

$Var = array ("String","anotherstring","sdfhs","dlj");

the above array will automatically be generated with a numeric index starting from 0.

$Array = array();
  $Array[] = "This is a string"; 

The above will push information into the array, as there has been no index or key specified. It will automatically be assigned with the closest numeric value to 0, which does not already exist in the array.

$Array = array();
  $Array['key'] = "This is another string"; 

The above will push information into the array also, but as we have specified an index with a string representation rather an automatically assigned value.

So the answer to your question, if i'm reading this Correctly.

If your referring to check if the array values are specified by PHP/The Code prior to reading the array. There is no soundproof method, as everything would need to be assigned to the array before it has data. further more, if your only adding elements to the array with a string key, then yes. It is possible.

If your relying on automatically generated numeric values, or assigning your own numeric values. it's impossible to tell if PHP has assigned this automatically, or you have specified.

Другие советы

There is no difference between explicit keys and implicit keys generated via []. The [] doesn't mean "give this element no key", it means "use the next key for this element".

Every element has a key

$arr1['a'] = 10; // key is the string 'a'
$arr2[] = 10;    // key is will be the integer zero
$arr3[2] = 10;   // key is the integer 2

Edit

Perhaps it would be good to understand why you wish to know if the index is automated or not? It seems odd.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top