I am actually to code an extension php (it's wirte in C
). Any way to know if a key exists in assoc array ? I use add_assoc_string
but this function erase data if key exist. Currently I do this :
array_init(return_value);
add_index_long(return_value, "key1", "value", 1);
add_index_long(return_value, "key2", "value6", 1);
add_index_long(return_value, "key1", "value2", 1); //here I erase previous key1 by value2
Is it possible to check if key1 for example is exists ? Maybe Can I use hashTable
but I find no example.
EDIT
I have finaly find solution, to check if key exist in zaval array
I do
if( zend_hash_exists(Z_ARRVAL_P(return_value), "key", sizeof("key")) ){
//key exist
}
You can use zend_hash_index_exists(Z_ARRVAL_P(return_value))
from here php-src.
Functions family starting from array_
is just wrappers to simplify usage of zend hash table API
. Look at the source code of array_init()
. You'll see that under the hood it calls zend_hash_init()
. So just use appropriate type casting in your code.
More examples how to work with arrays/hast tables in phpinternalsbook. Also you always can find a lot of useful examples directly in PHP source code repo. For example for this particular case - here.
PS: Also, it looks like this code is not working:
...
add_index_long(return_value, "key1", "value", 1);
because the real signature is add_index_long(zval *arg, zend_ulong idx, zend_long n)
, so one cannot use "key1" as zend_ulong idx
and "value" as zend_long n
due to type mismatch.