php Array storing key from a foreach loop into string - php

I have a key-pair array like this
$option['33']="Steak Doness";
$option['34']="Size";
$option['35']="Cooking Method";
I want to store the keys into a string like this
$key="33,34,35,";
I try to use foreach loop
$key="";
foreach($option as $key => $value) {
$key=$key.",";
}
echo $key;
However, my output is
35,
May i know which part went wrong?

You miss use the $key in your script.
The problem is with the $key which is in the foreach loop.... In each time your $key variable updated with the loop... Try with difference variable in your script.
OR, simply use
echo $key = implode(",", array_keys($option));

1st change your varible $key to $keys
replace one line
$key=$key.",";
to
$keys .= $key . ",";
it will work 100%

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

Can't access original array in foreach loop

I have a problem with my foreach loop. My foreach loop basically looks like this:
echo $values[0];
echo $values[1];
foreach ($values as $key => $value)
{
echo $values[0];
echo $values[1];
}
$values[0] should be "new york city" and $values[1] should be "new york". The problem is that in the foreach loop, both echos give the same value, whereas outside the loop they give the different (correct) values.
How do I access the original array ($values) normally inside of the foreach loop?
EDIT: I don't want to access the value $value. I want to be able to access any index of $values regardless of which iteration my foreach loop is on. I hope I am making sense.
Also, obviously I have alot more going on in this foreach loop, it was just meant as an example. The purpose of the foreach loop is not to print out these values.
Basically what the actual foreach loop I am using does is that it iterate through an array, and when it finds a certain value in that array, it iterates through the whole array again (inside the foreach loop). So basically I want a foreach loop inside a foreach loop, both for the same array, but it doesn't seem to work.
Try to use $val instead of $values[$i];
// Code goes here
foreach ($values as $key => $value)
{
echo $value;
}

Getting values after foreach loops

I have a foreach loop that gives me a number of values after looping through an array, like so:
842,844,841,839,838
This is the loop:
foreach ($values as $valuesKey => $value) {
echo $valuesKey . ',';
}
I need to work with those values after the loop finishes, how can I go about it? I want to put the list of values into another function. Is this even possible??
do_shortcode('[playlist type="audio" ids="/* values should go here */"][/playlist]');
It's supposed to look like this if it works:
do_shortcode('[playlist type="audio" ids="842,844,841,839,838"][/playlist]');
Thanks for anyone who can point me into the right direction!
There's no need for a loop. You can use implode() to join the array keys into a comma-separated string:
do_shortcode('[playlist type="audio" ids="'.implode(',', array_keys($values)).'"][/playlist]');
Try this
implode(",", array_keys($values))
Check it:
$val = array();
foreach ($values as $valuesKey => $value) {
$val[] = $valuesKey;
}
$val = implode(",", $val);
do_shortcode('[playlist type="audio" ids="'.$val.'"][/playlist]');

PHP Iterating Through Associative Array

So I have the following, working code:
$arrayitertest=Array("Fruit"=>Array("Pear","Peach","Apple","Banana"),"Cars"=>Array("My budget","other cars."));
foreach ($arrayitertest as $key=>$value)
foreach($arrayitertest[$key] as $result) echo $key.":". $result."|";
But when I change foreach ($arrayitertest as $key => $value) to foreach ($arrayitertest as $key) it throws a fatal error (despite the fact I never use the $key variable.)
The Error is:Invalid argument supplied for foreach() in
Could someone be so kind as to tell me why that happens ?
Edit: Wow, thanks for all the answers.... I will give the accept to the most specific one as of this moment though.
As far as your error is concerned: If you remove the $value from the first foreach, $key becomes the value and $arrayitertest[$key] becomes "pear" which is an invalid argument for the second foreach.
Your program would halt on:
// this is not going to work
foreach ("pear" as $result)
If you don't need the key of the first foreach you can just change it to:
foreach ($arrayitertest as $value)
{
foreach($value as $result)
{
}
}
I think you are misunderstanding the order of key and values. Where you say $value => $key it's technically $key => $value.
The way to parse your array is this:
foreach ($array as $key => $value) {
foreach ($array[$key] as $v) {
// $v = Pear (1st iteration), Peach (2nd), Apple (3rd) ... (for key = Fruit)
// $v = My Budget (1st iteration), other cars. (2nd) (for key = Cars)
// notice that $key is also accessible here
}
}
Obviously if you don't need the $key either you can simply:
foreach ($array as $a)
foreach ($a as $v)
// use $v here
Coding $value => $key, puts Fruit, Car, ... into $value.
Coding just $value puts the arrays such as Array("Pear","Peach","Apple","Banana") into $value and that is not a valid index for an array.

Using foreach effectively in PHP

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.

Categories