simon simon - 1 year ago 141
PHP Question

PHP extension check if key exist

I am actually to code an extension php (it's wirte in

). Any way to know if a key exists in assoc array ? I use
but this function erase data if key exist. Currently I do this :


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
but I find no example.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download