Iteration and modification of array best approach - php

The following is the best way to iterate through and modify array in PHP5.*+
(source: http://zend-php.appspot.com/questions_list -- question #3)
$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
$val += 1;
}
What is it about this method of iterating and modifying that makes it better than others?
Can someone please explain how come this actually works?
This iterates just fine, why include as $key => &$val if we are not using the keys?, also why do we need to include the & in &$val:
foreach($array as $val){
echo $val;
}
I appreciate the explanation,
Thanks in advance!

Since they intend to modify the value, getting it as a reference is clever.
$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
$val += 1;
}
Will add 1 to all values.
If you did:
foreach($array as $key => $val) {
$val += 1;
}
Nothing would happen.
I strongly disagree that it is the best way though. I much prefer to see:
foreach($array as $key => $val) {
$array[$key] += 1;
}
because it's much more straightforward. I'll gladly believe it doesn't perform as well, but I also don't care (unless there is a reason to start optimizing).
It's also worth mentioning that using references can lead to strange situations, such as: PHP reference causes data corruption
PS. I didn't downvote. I'm getting really annoyed by people downvoting and not leaving a comment.

The question is as follows:
What is the best way to iterate and modify every element of an array using PHP 5?
These are the four choices listed in the link:
// method one
for($i = 0; $i < count($array); $i++) {
/* ... */
}
// method two
foreach($array as $key => &$val) {
/* ... */
}
// method three
foreach($array as $key => $val) {
/*... */
}
// method four
while(list($key, $val) = each($array)) {
/* ... */
}
The options 1, 3 and 4 are okay and they will work for iterating through the array. However, to modify the original array, you'll need to pass the $val by reference, which is what the second option does. That's why it's the preferred solution, in this case.

Related

Array's key and value into a string

I'm currently new to coding and I'm trying to complete an exercise I have. I've tried to figure this out on my own, for hours now and for the life of me I can't seem to get it right... Here is the question:
''Create an array with the keys: "one", "two", "three", "four" and
"five" and the values: 1, 2, 3, 4, 5. Use a foreach-loop to add all keys and values to an array in the format: ["key"=value, "key"=value, etc]. Use implode() to make the answer a string with all items separated by a
comma ,.''
The code I have written is as follows:
$words = ["one", "two", "three", "four", "five"];
$numbas = [1, 2, 3, 4, 5];
$combined = array_combine($words, $numbas);
foreach ($combined as $key => $value) {
$forimplode = "$key = $value";
}
$imploded = implode(",", $forimplode);
$ANSWER = $imploded;
To me, this looks perfectly fine, but Yeah, I don't know what is going wrong. I really don't.. Haha.. I appreciate all help I'll be given and I'll sure to learn from my mistakes.
To me, this looks perfectly fine
And to me - not. Because every iteration of foreach overwrites $forimplode with a new string value. Instead, $forimplode should be declared as array and on each iteration new string should be add as a new item to $forimplode:
$forimplode = array();
foreach ($combined as $key => $value) {
$forimplode[] = "$key = $value";
}
$imploded = implode(",", $forimplode);
You are redeclaring your array every single time the for loop runs. Try this:
$forimplode = array();
foreach ($combined as $key => $value) {
$forimplode[] = "$key = $value";
}

Is there a way to loop through a multidimensional array without knowing it's depth?

So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.
e.g for two dimensions
foreach($array as $key=>$value)
{
foreach($value as $k2=>$v2)
{
echo
}
}
What do I do when I don't know the depth of the array? ie the depth is variable.
The only thing I can think of is to code a whole stack of loops and to break the loop if the next value is not an array.This seems a little silly.
Is there a better way?
Yes, you can use recursion. Here's an example where you output all the elements in an array:
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $v) {
printAll($v);
}
}
$array = array('hello',
array('world',
'!',
array('whats'),
'up'),
array('?'));
printAll($array);
What you should always remember when doing recursion is that you need a base case where you won't go any deeper.
I like to check for the base case before continuing the function. That's a common idiom, but is not strictly necessary. You can just as well check in the foreach loop if you should output or do a recursive call, but I often find the code to be harder to maintain that way.
The "distance" between your current input and the base case is called a variant and is an integer. The variant should be strictly decreasing in every recursive call. The variant in the previous example is the depth of $a. If you don't think about the variant you risk ending up with infinite recursions and eventually the script will die due to a stack overflow. It's not uncommon to document exactly what the variant is in a comment before recursive functions.
You can do the below function for loop-through-a-multidimensional-array-without-knowing-its-depth
// recursive function loop through the dimensional array
function loop($array){
//loop each row of array
foreach($array as $key => $value)
{
//if the value is array, it will do the recursive
if(is_array($value) ) $array[$key] = loop($array[$key]);
if(!is_array($value))
{
// you can do your algorithm here
// example:
$array[$key] = (string) $value; // cast value to string data type
}
}
return $array;
}
by using above function, it will go through each of the multi dimensional array, below is the sample array you could pass to loop function :
//array sample to pass to loop() function
$data = [
'invoice' => [
'bill_information' => [
'price' => 200.00,
'quantity' => 5
],
'price_per_quantity' => 50.00
],
'user_id' => 20
];
// then you can pass it like this :
$result = loop($data);
var_dump($result);
//it will convert all the value to string for this example purpose
You can use recursion for this problem:
Here is one example
$array = array(1 => array(1 => "a", 2 => array(1 => "b", 2 => "c", 3 => array(1 => "final value"))));
//print_r($array);
printAllValues($array);
function printAllValues($arr) {
if(!is_array($arr)) {
echo '<br />' . $arr;
return;
}
foreach($arr as $k => $v) {
printAllValues($v);
}
}
It will use recursion to loop through array
It will print like
a
b
c
final value
Simple function inside array_walk_recursive to show the level of nesting and the keys and values:
array_walk_recursive($array, function($v, $k) {
static $l = 0;
echo "Level " . $l++ . ": $k => $v\n";
});
Another one showing use with a reference to get a result:
array_walk_recursive($array, function($v) use(&$result) {
$result[] = $v;
});
Based on previous recursion examples, here is a function that keeps an array of the path of keys a value is under, in case you need to know how you got there:
function recurse($a,$keys=array())
{
if (!is_array($a))
{
echo implode("-", $keys)." => $a <br>";
return;
}
foreach($a as $k=>$v)
{
$newkeys = array_merge($keys,array($k));
recurse($v,$newkeys);
}
}
recurse($array);

Getting Data From Multi-level Array

Question below.
This is the solution I came up with based on Pixeler's answer.
<?php
$i = 0;
foreach ($array as $k1 => $v1) {
if (is_array($v1)) {
echo $k1."<br />";
foreach ($v1 as $k2 => $v2) {
echo "--".$k2."<br />----".$v2."<br />";
}
$i++;
}
echo "<br /<br />";
}
?>
<?php
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
?>
Is it possible to take what's above and get the text for each value by calling a number?
How could I do something like this?...
<?php
echo $array[0];
//Outputs "Apples"
echo $array[0][0];
//Outputs "Red"
echo $array[0][0][0];
//Outputs "$2.95"
echo $array[3][2][1];
//Outputs "$3.25" (Grapes > Green > Price)
?>
EDIT: The idea is that I can return the first level (Apples, Oranges, Grapes), second level (Red, Green, Navel, Purple, Green), and third level ($2.95, $2.45, $4.95, $3.75, $3.25) by calling a number.
For example, I want to do something like this:
<?php
count($array); //returns 3 (Apples, Oranges, Grapes)
//Do some for/foreach function that will produce the following:
//Apples
//->Red: $2.95
//->Green: $2.45
//Oranges
//->Navel: $4.95
//Grapes
//Purple: $3.75
//Green: $3.25
//I'm hoping to structure the code like this:
foreach($i = 0; $i =< count($array); $i++){
//echo title of array (Apples)
//echo each child key and it's value (Red: $2.95; Green: $2.45)
foreach($secondcounter = 0; $secondcounter =< count($array[$i]); $secondcounter++){
echo array_key($array[$i][$secondcounter]) . ": " .$array[$i][$secondcounter];
//Note: I don't actually know if array_key does the trick or not, it's meant to return "Red" in this case, while the non array_key()'d is meant to return the price of red apples, $2.95
}
?>
EDIT: It is important to note that I cannot use words to call the data. I must use numbers, i.e. [0] to call the first item in the array, because Apples could change depending on what row of data I load from my database. In other words... Apples could actually turn out to be Books, and Red could turn out to be the name of the book => price.
I'm intending on using serialize/unserialize to store and retrieve the data from the database, although I'm not overly familiar with these functions, I had a brief look at them and they seem reasonably easy to use.
I've been researching for hours but I cant find anything.
It is vital that I am able to call the data by numbers, not text. So $array["Apples"] is unacceptable.
I have also looked at json_decode and serialize/unserialize, and I think I get the basic idea of them from a brief look... but I think my main issue is understanding how to call the above data as presented in my example. Any help would be really great.
This is the solution I came up with based on #Pixeler's answer.
<?php
$i = 0;
foreach ($array as $k1 => $v1) {
if (is_array($v1)) {
echo $k1."<br />";
foreach ($v1 as $k2 => $v2) {
echo "--".$k2."<br />----".$v2."<br />";
}
$i++;
}
echo "<br /<br />";
}
?>
What about this one?
array_search("Apples",array_keys($array));
If you want to loop your array one way or another you might have to create new array, loop through your old array and create new numeric array array?
FIRST WAY
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
$newArray = array();
foreach ($array as $value) {
$newArray[] = (is_array($value)) ? array_values($value) : $value;
}
echo '<pre>';
var_dump($newArray);
echo '</pre>';
SECOND WAY
$array = array( "Apples" => array("Red" => "$2.95", "Green" => "$2.45"),
"Oranges" => array("Navel" => "$4.95"),
"Grapes" => array("Purple" => "$3.75", "Green" => "$3.25")
);
$newArray = array();
$i = 0;
foreach ($array as $key => $value) {
if (is_array($value)) {
$newArray[$i] = array();
foreach ($value as $k => $v) {
$newArray[$i][] = $v;
}
$i++;
}
}
echo '<pre>';
var_dump($newArray);
echo '</pre>';
echo $newArray[0][0];
Obviously I will recommend first way.

Reset/remove all values in an array in PHP

I have an array_flipped array that looks something like:
{ "a" => 0, "b" => 1, "c" => 2 }
Is there a standard function that I can use so it looks like (where all the values are set to 0?):
{ "a" => 0, "b" => 0, "c" => 0 }
I tried using a foreach loop, but if I remember correctly from other programming languages, you shouldn't be able to change the value of an array via a foreach loop.
foreach( $poll_options as $k => $v )
$v = 0; // doesn't seem to work...
tl; dr: how can I set all the values of an array to 0? Is there a standard function to do this?
$array = array_fill_keys(array_keys($array), 0);
or
array_walk($array, create_function('&$a', '$a = 0;'));
You can use a foreach to reset the values;
foreach($poll_options as $k => $v) {
$poll_options[$k] = 0;
}
array_fill_keys function is easiest one for me to clear the array. Just use like
array_fill_keys(array_keys($array), "")
or
array_fill_keys(array_keys($array), whatever you want to do)
foreach may cause to decrease your performance to be sure that which one is your actual need.
Run your loop like this, it will work:
foreach( $poll_options as $k => $v )
$poll_options[$k] = 0;
Moreover, ideally you should not be able to change the structure of the array while using foreach, but changing the values does no harm.
As of PHP 5.3 you can use lambda functions, so here's a functional solution:
$array = array_map(function($v){ return 0; }, $array);
You have to use an ampersand...
foreach( $poll_options as &$v)
$v = 0;
Or just use a for loop.
you can try this
foreach( $poll_options as $k => &$v )
$v = 0;
Address of $v
array_combine(array_keys($array), array_fill(0, count($array), 0))
Would be the least manual way of doing it.
There are two types for variable assignment in PHP,
Copy
Reference
In reference assignment, ( $a = &$b ), $a and $b both, refers to the same content. ( read manual )
So, if you want to change the array in thesame time as you doing foreach on it, there are two ways :
1- Making a copy of array :
foreach($array as $key=>$value){
$array[$key] = 0 ; // reassign the array's value
}
2 - By reference:
foreach($array as $key => &$value){
$value = 0 ;
}

Exploding Arrays in PHP While Keeping the Original Key

How can I do the following without lots of complicated code?
Explode each value of an array in PHP (I sort of know how to do this step)
Discard the first part
Keep the original key for the second part (I know there will be only two parts)
By this, I mean the following:
$array[1]=blue,green
$array[2]=yellow,red
becomes
$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow
I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.
given this:
$array[1] = "blue,green";
$array[2] = "yellow,red";
Here's how to do it:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
Another way you could do it would be like this:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
... or use a combination of substr() and strpos()
Try this:
$arr = explode(',','a,b,c');
unset($arr[0]);
Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:
list(,$what_i_want) = explode('|','A|B',2);
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
The array you start with:
$array[1] = "blue,green";
$array[2] = "yellow,red";
One way of coding it:
function reduction($values)
{
// Assumes the last part is what you want (regardless of how many you have.)
return array_pop(explode(",", $values));
}
$prime = array_map('reduction', $array);
Note: This creates a different array than $array.
Therefore $array == $prime but is not $array === $prime

Categories