I'm trying to pass key values pairs within PHP:
// "initialize"
private $variables;
// append
$this->variables[] = array ( $key = $value)
// parse
foreach ( $variables as $key => $value ) {
//..
}
But it seems that new arrays are added instead of appending the key/value, nor does the iteration work as expect. Please let me know what the proper way is.
Solution
$this->variables[$key] = $value;
did the trick - the iteration worked as described above.
I think you may be looking for:
$this->variables[$key] = $value;
The way you have it right now you are creating an array of arrays, so you would have to do this:
foreach($this->variables as $tuple) {
list($key, $value) = $tuple;
}
Referring to Perl, but helps understand the difference between hashes and arrays:
Some people think that hashes are like arrays (the old name 'associative array' also indicates this, and in some other languages, such as PHP, there is no difference between arrays and hashes.), but there are two major differences between arrays and hashes. Arrays are ordered, and you access an element of an array using its numerical index. Hashes are un-ordered and you access a value using a key which is a string.
Source: http://perlmaven.com/perl-hashes
Related
I feel like i'm missing something quite simple. What are some of the best ways to iterate through combinations of $key names -- doing something different for each-- in a php foreach loop?
I have a number of values in an array with key values that follow the same naming format.
Example:
$rec_items['title3'] = implode($meta['title3']);
$rec_items['title4'] = implode($meta['title4']);
$rec_items['title5'] = implode($meta['title5']);
The $rec_items array also contains other values that do not follow this naming convention (or data type).
I'm looping through $rec_items with a foreach loop. I would like to be able to dynamically cycle through key names in $rec_items, and 'do something' when a key is found that matches title*. I've tried pushing numeric numbers from a counter variable into key names to be searched for (like below):
foreach ($rec_items as $key => $value){
$c = 0;
if(!empty($key[${'title'.$c}]){
$c++;
//do something
}
I believe that I cannot pass the value ${'title'.$c} into $key[] and have tried to pass the value of ${'title'.$c} as a string with no luck.
I just share the above to try to highlight what i'm trying to achieve.
(1) dynamically loop through key names in the format 'title*'
(2) if the key name is present in the $rec_items array ... do something.
I'm not sure what your original code was trying for; you appeared to be treating the array key like an array itself? Using a variable variable? Anyway, you just need a simple string search of the key. You can use regular expressions or whatever you like for more complex matching.
<?php
$rec_items = ["foo"=>12, "bar"=>34, "title1"=>56, "title2"=>78, "baz"=>90];
foreach ($rec_items as $k=>$v) {
if (strpos($k, "title") === 0) {
echo "$k = $v\n";
}
}
Output:
title1 = 56
title2 = 78
I have the following array
$a = ["one", "dos" => "two", "three"];
As you see the second element has the key for his value set explicitely, but the other 2 items do not.
I want to loop through the array, but do something different, depending if the key for that item was set explicitly or not. Kinda like this:
foreach($a as $value){
if( has_explicit_key($value) )
// Do something
else
// Do other stuff
}
How can I achieve this?
PS: I guess I could check if the key is an integer, but if the key is set explicitly as an integer, that would not work, right?
try this
foreach($a as $key=>$value){
if( is_int($key) )
// Do something
else
// Do other stuff
}
this is the closest approach since keys are usually, 0,1,2......
In your specific case, you can exploit the fact that elements without explicit string keys automatically receive integer indexes:
$a = ["one", "dos" => "two", "three"];
foreach ($a as $k => $v) {
if (is_int($k)) {
// Do something
} else {
// Do other stuff
}
}
If you allow for the explicit keys to be scalars other than strings (integer, float, boolean, etc), then there is no way (at run-time) to distinguish between non-string keys supplied by the user and integer keys filled in by the parser. Specifically, refer to the PHP source function zend_ast_add_array_element. In that function, when the key is not explicitly given (offset IS_UNDEF), then PHP assigns one with zend_hash_next_index_insert and records no bookkeeping note of that fact.
Now, if you don't mind, and are capable of statically analyzing the data structure, just tokenize or parse the PHP code and see if T_DOUBLE_ARROW precedes the array value. This is probably not worth the effort and only works on static code.
You can loop through the array using
foreach($a as $key => $value) {
/* stuff */
}
To check if the key has been set explicitly can probably only be done by checking if the key is numerical (PHP will assign numerical keys to values without any keys in arrays).
Of course this means that you won't be able to detect a key that was set explicitly and is numeric.
So unless there's some function (which I'm unaware of) this would be the only way.
I looping through a large dataset (contained in a multidimensional associative array $values in this example) with many duplicate index values with the goal of producing an array containing only the unique values from a given index 'data'.
Currently I am doing this like:
foreach ($values as $value) {
$unique[$value['data']] = true;
}
Which accomplishes the objective because duplicate array keys simply get replaced. But this feels a bit odd since the indexes themselves don't actually contain any data.
It was suggested that I build the array first and then use array_unique() to removes duplicates. I'm inclined to stick with the former method but am wondering are there pitfalls or problems I should be aware of with this approach? Or any benefits to using array_unique() instead?
I would do it like this.
$unique = array();
foreach($values as $value) {
if(!in_array($value, $unique) {
$unique[] = value;
}
}
I am tring to do (like) a 2 dimensional array, case insensitive.
I have:
foreach ($rows as $key=>$row) {
$names[$key]=$row['Name'];
}
array_multisort($rows,SORT_STRING|SORT_FLAG_CASE,$names);
The above ends up producing the same result (with or without case flag).
Sick of staring at this, any ideas from somebody outside?
First of all SORT_FLAG_CASE is only available in PHP v5.4+ so I suggest checking which version of PHP you are running (maybe 'uksort' could help if 5.3ish).
If not, make sure all the values that you put into $names lowercase or uppercase.
You have the order of the arguements $rows and $names reversed in the call to array_multisort.
Lastly if it comes from a database (or some other manner that means you cant change the data on the way into the array) then you can use array_walk.
Hope that helps
Since I ran into this with PHP 5.3.16, I thought I'd share my simple solution: just convert your keys to lower (or upper) case, e.g.:
foreach ($rows as $key=>$row) {
$names[$key]=strtolower($row['Name']);
}
array_multisort($names,SORT_STRING,$rows);
I also swapped the $rows & $names and removed the SORT_FLAG_CASE (to get rid of the log message).
You can also do a sort within a sort, so you can use usort with strcasecmp:
foreach ($rows as $key=>$row) {
$names[$key]=row['Name'];
}
array_multisort(usort($names,strcasecmp),$rows);
Above answer didn't work, because the first array got mingled while the other one didn't. So I wrote a general multidimensional array case insensitive compare function. It also can use multiple keys:
function array_casecmp($keys) {
if (gettype($keys) != "array") $keys = func_get_args();
return function ($a, $b) use ($keys) {
foreach($keys as $value) {
$akeys = $akeys . $a[$value];
$bkeys = $bkeys . $b[$value];
}
return strcasecmp($akeys, $bkeys);
};
}
Use it like:
usort($files,strcasecmp(array(0,1)); // with standard array
usort($files,strcasecmp(1); // single key
usort($files,strcasecmp(0,1); // arguments are converted to array
usort($files,strcasecmp("dir","link")); // you can also use symbolic keys
usort($files,strcasecmp(0,1,2,3,4,...); // use as many keys as you like
Keep in mind that the keys are concatenated, so maybe you have to use str_pad in your array colums to keep them seperated in the right way.
I can't find an answer to this anywhere.
foreach ($multiarr as $array) {
foreach ($array as $key=>$val) {
$newarray[$key] = $val;
}
}
say $key has duplicate names, so when I am trying to push into $newarray it actually looks like this:
$newarray['Fruit'] = 'Apples';
$newarray['Fruit'] = 'Bananas';
$newarray['Fruit'] = 'Oranges';
The problem is, the above example just replaces the old value, instead of pushing into it.
Is it possible to push values like this?
Yes, notice the new pair of square brackets:
foreach ($multiarr as $array) {
foreach ($array as $key=>$val) {
$newarray[$key][] = $val;
}
}
You may also use array_push(), introducing a bit of overhead, but I'd stick with the shorthand most of the time.
I'll offer an alternative to moonwave99's answer and explain how it is subtly different.
The following technique unpacks the indexed array of associative arrays and serves each subarray as a separate parameter to array_merge_recursive() which performs the merging "magic".
Code: (Demo)
$multiarr = [
['Fruit' => 'Apples'],
['Fruit' => 'Bananas'],
['Fruit' => 'Oranges'],
['Veg' => 'Carrot'],
//['Veg' => 'Leek'],
];
var_export(
array_merge_recursive(...$multiarr)
);
As you recursively merge, if there is only one value for a respective key, then a subarray is not used, if there are multiple values for a key, then a subarray is used.
See this action by uncommenting the Leek element.
p.s. If you know that you are only targetting a single column of data and you know the key that you are targetting, then array_column() would be a wise choice.
Code: (Demo)
var_export(
['Fruit' => array_column($multiarr, 'Fruit')]
);