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];
Related
I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:
$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
'MailTo1' => 6143,
'MailTo2' => 6137,
'MailTo3' => 6137,
);
echo $mailTo['MailTo1']; //6143
$result1['needle'] = 'MailTo1'; //needle from second query to seek
if(in_array($result1['needle'], $mailTo)){
$id['mailTo'] = $mailTo[$result1['needle']]; //null
}
using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:
if(in_array('MailTo1', $mailTo)){
$id['mailTo'] = $mailTo[$result['needle']]; //6143
}
Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.
$result = 'MailTo1';
if(in_array($result1, $mailTo)){
$id['mailTo'] = $mailTo[$result1]; //null
}
I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...
In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.
array_key_exists("MailTo1",$mailTo)
Another approach would be to get all keys in one array and then you can use in_array()
$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
DOH!!! Wrong approach.. array_key_exists is what I should have been using!!
$test = ['hi'=>['ho'=>1] ];
$str = 'hi[ho]';
var_dump ( isset($test[$str] ) );
In this example the variable test has a key of 'hi' and the key 'hi' is a multidimensional array with another key of 'ho'.
I am looking for a way to access the ['hi']['ho'] via a string. Something akin to $test[$str] .
This is a simplified example and the real code will have multidimensional arrays with up to 10 deep, but the concept will still be the sam.e
Why does the below code not assume an empty 'value' pair for the specified 'key'?
Take the following example:
$key1 = "An element";
$key2 = "Another, without a pair";
$key3 = "A third, with a pair";
$check=Array($key1=>21, $key2, $key3=>23);
If outputted using print_r, returns the following:
Array ( [An element] => 21 [0] => Another, without a pair [A third, with a pair] => 23 )
Rather than:
Array ( [An element] => 21 [Another, without a pair] => null [A third, with a pair] => 23 )
I want to have an array containing an unknown number of items, all of which may or may not have a key=>value pair. What are my options for ensuring that I get the second result?
Essentially, I want to pass a list of keys from my controller to a function, and for the function to identify them as key->value even if the value is null. Some of the keys might have values set, others might not.
It may be that the best solution lies in the foreach $key as $value {} code space, or that I can wrap $key1 in some form of parenthesis... I'm not sure!
Thanks
Add NULL as shown here.
$check=Array($key1=>21, $key2=>NULL, $key3=>23);
To Initialize the array:
$keys = array($key1, $key2, $key3);
$check = array_fill_keys($keys,NULL);
It depends in the type of the values.
Using NULL is a very common technique, But, if all values, are intended to be of the same type, maybe you would like to use an "empty" value for them, that is not NULL.
Example, if the values are integers, you may want to use 0 or -1 to indicate the value is not assigned. Or "" for strings.
In case that you are storing different types, then, you may like to use NULL as a non typed value.
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];
<?php $postid[] = get_the_ID(); // capture the id (a number) ?>
Now If I echo $postid I just get: Array
and when I do the following:
<?php
$default = array(
'posts_per_page' => $postid
);
?>
I don't get anything either.
Any suggestions?
When working with arrays in PHP, you can use the following to assign an array to a variable :
// initalize empty array
$a = array();
var_dump($a);
(The array() could be non-empty, of course)
Or you can use the following syntax, without the indexes :
// push items at the end of the array
$a[] = 10;
$a[] = 20;
var_dump($a);
And, finally, you can set an item at a key of your choice :
// put an item at a given index
$a['test'] = 'plop';
var_dump($a);
For more informations, see the Arrays sections of the manual.
Doing so, thanks to the three var_dump() calls, I'll get :
array
empty
array
0 => int 10
1 => int 20
array
0 => int 10
1 => int 20
'test' => string 'plop' (length=4)
Note : many use print_r() instead of var_dump() -- I tend to prefer var_dump(), which displays more informations, especially when the Xdebug extension is installed.
But note that, in any case, calling echo on an array itself :
echo $a;
Will get nothing else as output than :
Array
Which is not quite useful ;-)
Still, you can display the value of a single item of that array :
echo $a['test'];
Which, in this case, would get you this output :
plop
Basically : echo is not what you should use when you want to display an array :
Either use var_dump() if you want to inspect an array for debugging purposes,
or loop over the array with foreach, displaying each item with echo
Note : you might have to do some recursion, to inspect sub-arrays ;-)