Associative array with similar keys assignment - php

Consider I have associative array with same key values:
$arr = {'MessageID' =>1 ,'MessageID' =>5 , 'MessageID' => 8};
Now I want every call to function foo() which will insert a new key value of 'MessageID'=>integer
How can we do that without overriding other existing key values pairs?

As many answerers before, you can't have keys with the same string in the array in PHP. If you want to represent multiple values per key I use something like this:
$arr = ['MessageID' => [1, 5, 8]];
You would append to MessageID with this code:
$arr['MessageId'][] = 10;
Then it would look like this:
['MessageID' => [1, 5, 8, 10]]
This worked well for me with HTTP headers and other things which are key value based, but can have multiple values.

In php array, you can not insert multiple values with same index.
If you want to use it then you can use it with following manner
$MessageID = array(1,5,8);
and
$MessageID[] = $newValue; to insert new value.

You cannot have an array with duplicate keys.
A better implementation would be to have an array called $messageIDs and save the actual values in the array:
$messageIDs = array (1, 5, 8);

As i mentioned in comments, you cannot have duplicate keys in an array. Also your sample with curly braces is not valid php syntax.
Perhaps you need a multidimentional array:
$arr = [['messageID'=>1],['messageID'=>5],['messageID'=>8]];
in which case you would add another value like so:
$arr[] = ['messageID'=>11];

Related

Using empty string as key in associative array

I need to select and group some items according to some values and it's easy using an associative multidimensional array:
$Groups = array(
"Value1" = array("Item1", "Item3"),
"Value2" = array("Item2", "Item4")
);
But some items hasn't the value so my array will be something like:
$Groups = array(
"Value1" = array("Item1", "Item3"),
"Value2" = array("Item2", "Item4")
"" = array("Item5", "Item6")
);
I've tested it (also in a foreach loop) and all seems to work fine but I'm pretty new to php and I'm worried that using an empty key could give me unexpected issues.
Is there any problem in using associative array with empty key?
Is it a bad practice?
If so, how could I reach my goal?
There's no such thing as an empty key. The key can be an empty string, but you can still access it always at $groups[""].
The useful thing of associative arrays is the association, so whether it makes sense to have an empty string as an array key is up to how you associate that key to the value.
You can use an empty string as a key, but be careful, cause null value will be converted to empty string:
<?php
$a = ['' => 1];
echo $a[''];
// prints 1
echo $a[null];
// also prints 1
I think, it's better to declare some "no value" constant (which actually has a value) and use it as an array key:
<?php
define('NO_VALUE_KEY', 'the_key_without_value');
$a = [NO_VALUE_KEY => 1];

php change the name to construct an associative array

Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.

Acessing an multidimentional array from a variable

I want to store the parents keys of an array so I can access it later.
Something like:
$arr['hello'][0]['world'] = 'a';
$arr['hello'][1]['world'] = 'b';
And store both hello, 0 and world as some kind of variable so I can access the array with it:
For example, something I would think it may work is:
$indexes = array('hello', 0, 'world');
$arr[$indexes]
But this doesn't work, as an array is an illegal offset type for another array. So is there a way to access an array by an array of parents keys (variable)?
i think you want
echo $array[{$one}][{$two}];
So do you want to access a child array by a custom key that occurs in a parent array?
$parent_array[$custom_key] = array('hello',0,'world');

php: get array value without iterating through it?

hey guys,
i think i lost my mind.
print_r($location); lists some geodata.
array (
'geoplugin_city' => 'My City',
'geoplugin_region' => 'My Region',
'geoplugin_areaCode' => '0',
'geoplugin_dmaCode' => '0',
'geoplugin_countryCode' => 'XY',
'geopl ...
when I iterate through it with a foreach loop I can print each line.
However shouldn't it be possible to just get a specific value out of the array?
like print $location[g4]; should print the countryCode shouldn't it? Thank you!
echo $location['geoplugin_countryCode'];
Yes, you can get a specific value by key. The keys in your case are the geoplugin_ strings.
To get the country code:
// XY
$location['geoplugin_countryCode'];
$location['geoplugin_countryCode'];
would access country code
Where does "g4" come from? Did you mean "4"?
If you had a normal numerically-indexed array then, yes, you could write $location[4]. However, you have an associative array, so write $location['geoplugin_countryCode'].
there you are using an associative array, it is an array with a user defined key:value pair (similar to dictionaries on Python and Hash Tables on C#)
You can access the elements just using the Key (in this case geoplugin_city or geoplugin_region)
Using the standard array syntax:
$arrayValue = $array[key]; //read
$array[key] = $newArrayValue; //write
For example:
$location['geoplugin_city']; or $location['geoplugin_region'];
If you are not familiarwith PHP arrays you can take a look here:
http://php.net/manual/en/language.types.array.php
For a better understanding on array manipulation with PHP take a look of:
http://www.php.net/manual/en/ref.array.php

php arrays (and removing certain element)

I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays

Categories