Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP associative arrays - how to treat integer as string

I have a simple associative array.

$a = array("a"=>"b", "c"=>"d");

I want to check if the key "1" exists in the array, e.g.

isset($a["1"]);

This string is being treated as an integer, so that

echo $a["1"]; //prints "d"

How do I get it to treat it as a string?

I don't want to use array_key_exists or in_array because my benchmarking shows isset will be a lot faster.

like image 856
bcoughlan Avatar asked Jan 09 '11 04:01

bcoughlan


People also ask

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you remove a key and its value from an associative array in PHP?

Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array. print_r( $arr ); ?> Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays.

How can we access a specific value in an associative array in PHP?

You can use the PHP array_values() function to get all the values of an associative array.


1 Answers

It doesn't appear that you can do what you want to do. from http://us.php.net/manual/en/language.types.array.php:

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").

You'll probably have to use Fosco's suggestion of prefixing all your keys with something. If you use the same prefix on every key, then it doesn't matter if you're parsing a text that might have words and numbers - put the same prefix on everything regardless.

like image 169
Michael Burr Avatar answered Oct 05 '22 03:10

Michael Burr