Having:
$a as $key => $value;
is the same as having:
$a=array();
?
No, it's not. It's more like
list($key, $value) = each($arr);
See the manual
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
is identical to
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
Also see
The while Control Structure
list — Assign variables as if they were an array
each — Return the current key and value pair from an array and advance the array cursor
reset — Set the internal pointer of an array to its first element
First of all it has to say
foreach($a as $key => $value)
Then, as far as I know,
foreach($a = array())
doesn't compile.
That said, if you foreach, you iterate through the elements of an array. With the 'as' keyword, you get pairs of key/value for each element, where $key would be the index by which you can get $value:
$value = $a[$key];
Did this answer your question? If not, please specify.
edit:
In other programming languages it would spell something like
foreach($key => $value in $a)
or (C#)
foreach(KeyValuePair<type1, type2> kv in a)
which I think is more intuitive, but basically the same.
if you have the following:
$a = array('foo' => array('element1', 'element2'), 'bar' => array('sub1', 'sub2'));
if you use $a as $key=> $value in the foreach loop,
$key will be 'foo', and $value will be array('element1', 'element2') in the first iteration, in the second $key == 'bar' and $value == array('sub1', 'sub2').
If you loop over an array using foreach, the array is the first expression inside the parenthesis.
It can be a variable, like $a, or an array literal like array(1, 2, 3). The following loops are identical:
With an array literal:
foreach(array(1, 2, 3) as $number)
print($number);
With a variable:
$a = array(1, 2, 3);
foreach($a as $number)
print($number);
Related
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";
}
I have a string that I converted to a multi-dimensional array.
String: 13,4,3|65,1,1|27,3,2
I wanna be able to move 27,3,2 to index 1 for example, so it would become:
13,4,3|27,3,2|65,1,1
Or remove one of those sections.
I know I can unset(), but I'm not sure how to search for an index then move it or unset it.
You can try the below one for interchanging the position of last two elements
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key] = $array[$key-1];
$array[$key-1] = $value;
}
}
This is for removing the second element.
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key-1] = $value;
unset($array[$key]);
}
}
Loop through the array using foreach
foreach($array as $key => $value)
From key you can get the key and can do whatever you like.
Other wise, you can do this if you know the key
echo $array['pass_key_name_here'];
I have an array like such:
array('some_key' => 'some_value');
I would like to take that and transform it to, this should be done programatically
array('some_key' => array('some_value'));
This should be rather simple to do but the only think I can find is answers on string split and explode, to explode strings into arrays. I thought PHP, like other languages, had something called to_array or toArray.
I am assuming this is super easy to do?
If you're just doing the one array element, it's as simple as:
$newarray['some_key'] = array($sourcearray['some_key']);
Otherwise if your source array will have multiple entries, you can do it in a loop:
foreach($sourcearray AS $key => $value) {
$newarray[$key] = array($value);
}
Something as simple as $value = array($value) should work:
foreach ($array as &$value) {
$value = array($value);
}
unset($value); //Remove the reference to the array value
If you prefer to do it without references:
foreach ($array as $key => $value) {
$array[$key] = array($value);
}
You can try like this
<?php
$arr=array('some_key' => 'some_value');
foreach($arr as $k=>$v)
{
$newarr[$k] = array($v);
}
var_dump($newarr);
I'm trying to increment the value for $variable each time a duplicate variable occurs. I'm not sure if this is syntactically correct, but I think this is semantically correct. var_dump seems to spit out the correct outputs, but i get this error: Notice: Undefined index...
$newarray = array();
foreach ($array as $variable)
{
$newarray[$variable]++;
var_dump($newarray);
}
$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=> o);
goal:
'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1
My code works, it's just that I get some weird NOTICE.
$newarray = array();
foreach ($array as $variable)
{
if (!isset($newarray[$variable])) {
$newarray[$variable] = 0;
}
$newarray[$variable]++;
}
Take a look at the function array_count_values(). It does exactly what you are trying to do.
Sample from php.net:
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
Result:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
In modern PHP, you can avoid the isset() call by leveraging the null coalescing operator. In the snippet below, the technique sets the variable to 0 if the variable is not yet declared. Then you can freely use a range of shorthand manipulations such as concatenation, arithmetic, etc.
$new = [];
foreach ($array as $v) {
$new[$v] = ($new[$v] ?? 0) + 1;
}
Or if you want to continue using ++, then you can use the "null coalescing assignment operator". The logic on the right side of assignment is not even executed if the variable is already declared. The below snippet will perform identically to the above snippet.
$new = [];
foreach ($array as $v) {
$new[$v] ??= 0;
++$new[$v];
}
<?php
$newarray = array();
foreach ($array as $variable) {
if ( !array_key_exists($variable, $newarray) ) {
$newarray[$variable] = 0;
}
++$newarray[$variable];
}
var_dump($newarray);
But you could also use array_count_values() instead.
$newarray = array();
foreach ($array as $variable)
{
if(!isset($newarray[$variable]))
$newarray[$variable] = 0;
$newarray[$variable]++;
var_dump($newarray);
}
You are incrementing the wrong thing, try this instead:
foreach ($array as $key => $variable) {
$array[$key]++;
var_dump($array);
}
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