Consider the following array-
$array = array("index1"=>"8787",
"index2"=>909,
"index3"=>"234234",
"index4"=>"00-00-0000",
"index5"=>"false",
"index6"=>"5432",
"index7"=>2834,
"index8"=>42847628
);
Is there a way to convert the non-string elements of the array into string type without actually traversing the array .
The array could be quite big as it is created dynamically and will affect the response time.
I could use the following
foreach ($array as $key => $value) {
$array[$key] = (gettype($value)=="string")?$value:(string)$value;
}
However,is there any better way?
You can doo this only by traversing. So, in such way using array_map:
$array = array("index1"=>"8787",
"index2"=>909,
"index3"=>"234234",
"index4"=>"00-00-0000",
"index5"=>"false",
"index6"=>"5432",
"index7"=>2834,
"index8"=>42847628
);
$result = array_map('strval',$array );
var_dump($result);
There are many solutions. You can also do it from within the foreach loop:
foreach ($array as $key => &$_value) {
$_value = strval($_value);
}
The & is important here. (The _ is just a convention I use to prevent me from mixing reference and non-reference variables.)
Related
I'm looking for a nifty php solution to replace a standard forloop. i dont care at all about the inner workings of my normalize method.
Here is my code:
$pairs=[];
foreach($items as $key => $val){
$key = $this->normalizeKey($key);
$pairs[$key] = $val;
}
private function normalizeKey($key)
{
// lowercase string
$key = strtolower($key);
// return normalized key
return $key;
}
I'd like to learn the PHP language a bit better. I thought array_walk would be nice to use, but that operates on the values and not the keys.
I am looking for a PHP array method that can perform this code instead of a foreach loop.
You want array_change_key_case
$pairs = array_change_key_case($items);
Just for fun, though it requires three functions. You can replace strtolower() with whatever since this can already be done with array_change_key_case():
$pairs = array_combine(array_map('strtolower', array_keys($items)), $items);
Get the keys from $items
Map the array of keys to strtolower()
Combine the new keys with $items values
You can also use an anonymous function as the callback if you need something more complex. This will append -something to each key:
$pairs = array_combine(array_map(function ($v) {
return $v . '-something';
},
array_keys($items)), $items);
You can normalise the keys and store them and their corresponding values in a temporary array and assign it to your original $pairs array.
Like so:
$normalised = [];
foreach($pairs as $key => $value) {
$normalised[$this->normalizeKey($key)] = $value;
};
$pairs = $normalised;
Edit 2022: Or better yet, use #Sherif's answer as it uses a standand library function
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')]
);
So I don't think I'm making full use of the foreach loop. Here is how I understand foreach.
It goes like foreach(arrayyouwanttoloopthrough as onevalueofthatarray)
No counter or incrementing required, it automatically pulls an array, value by value each loop, and for that loop it calls the value whatever is after the "as".
Stops once it's done with the array.
Should basically replace "for", as long as dealing with an array.
So something I try to do a lot with foreach is modify the array values in the looping array. But in the end I keep finding I have to use a for loop for that type of thing.
So lets say that I have an array (thing1, thing2, thing3, thing4) and I wanted to change it....lets say to all "BLAH", with a number at the end, I'd do
$counter = 0;
foreach($array as $changeval){
$counter++;
$changeval = "BLAH".$counter;
}
I would think that would change it because $changeval should be whatever value it's at for the array, right? But it doesn't. The only way I could find to do that in a] foreach is to set a counter (like above), and use the array with the index of counter. But to do that I'd have to set the counter outside the loop, and it's not even always reliable. For that I'd think it would be better to use a for loop instead of foreach.
So why would you use foreach over for? I think I'm missing something here because foreach has GOT to be able to change values...
Thanks
OH HEY One more thing. Are variables set in loops (like i, or key) accessible outside the loop? If I have 2 foreach loops like
foreach(thing as value)
would I have to make the second one
foreach(thing2 as value2) ]
or else it would have some problems?
You can use a reference variable instead:
foreach ($array as &$value)
{
$value = "foo";
}
Now the array is full of foo (note the & before $value).
Normally, the loop variable simply contains a copy of the corresponding array element, but the & (ampersand) tells PHP to make it a reference to the actual array element, rather than just a copy; hence you can modify it.
However, as #Tadeck says below, you should be careful in this case to destroy the reference after the loop has finished, since $value will still point to the final element in the array (so it's possible to accidentally modify it). Do this with unset:
unset($value);
The other option would be to use the $key => $value syntax:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
To answer your second question: yes, they are subsequently accessible outside the loop, which is why it's good practice to use unset when using reference loop variables as in my first example. However, there's no need to use new variable names in subsequent loops, since the old ones will just be overwritten (with no unwanted consequences).
You want to pass by reference:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
{
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
The extended foreach syntax is like this:
foreach ($array as $key => $value) {
}
Using the $key, you can index the original array:
foreach ($array as $key => $value) {
$array[$key] = "BLAH";
}
Incrementing from 0 to ...
foreach($array as $changeval){
if (!isset($counter)) { $counter = 0; }
$counter++;
$changeval = "BLAH".$counter;
}
Using the index/key of the ARRAY
foreach($array as $key => $changeval){
$changeval = "BLAH".$key;
}
You can use the key when looping with foreach:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
But note that using a reference like Will suggested will be faster for such a case - but anyway, the $key => $value-syntax is quite useful sometimes.
given the following arrays in php, how can i best merge them together
$masterkeys = array('Key1','Key2');
$settings_foo = array(
array('ID'=>'Key1',
'Foo_Setting'=>'SomeValue'));
$settings_bar = array(
array('ID'=>'Key1',
'Bar_Setting'=>'SomeOtherValue'));
in the end I need $masterkeys to be the combination of each of the settings_[foo|bar] arrays.
Array( ['Key1'] = Array('Foo_Setting'=>'SomeValue','Bar_Setting'=>'SomeOtherValue') );
I do know I can use a couple foreach loops on this, but just wondering if there are a couple PHP array functions that can splice them together.
While you can use some of PHP's array functions, your input data isn't in a very nice format. You'll have the fewest iterations (and probably best performance) by writing them yourself:
# create an array of $masterkey => array()
$result = array_combine($masterkeys, array_fill(0, count($masterkeys), array()));
# loop through each settings array
foreach (array($settings_foo, $settings_bar) as $settings)
{
foreach ($settings as $s)
{
# merge the array only if the ID is in the master list
$key = $s['ID'];
if (array_key_exists($key, $result))
$result[$key] = array_merge($result[$key], $s);
}
}
# unset all extraneous 'ID' properties
foreach (array_keys($result) as $i)
unset($result[$i]['ID']);
var_dump($result);
As an alternative, you could look into array_map and array_filter, but due to the way the data is structured, I'm not sure they'll be of much use.
I'm not sure how your $masterkeys array plays in here, but array_merge_recursive may do what you want.
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