foreach $key variable clarification - php

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.

Related

PHP array, substitute the key within a foreach loop

I have read a lot of posts and have not been able to find a solution to my issue.
I have a $_POST array named "Water", $_POST['Water'] and its contents are:
[Water] => Array ( [0] => 55.0 [1] => 22 )
Is it possible to use the name of the post inside a foreach loop so the $key could use the name "Water":
foreach($_POST['Water'] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
Many thanks for your time.
Not really. foreach() operates on the contents of an array. Whatever actually contains that array is outside of foreach's view. If you want to dynamically use the Water key elsewhere, you'll have to do that yourself:
$key = 'Water'
foreach($_POST[$key] as $val) {
$fields[] = "$key = '$val'";
}
If I read this right you basically want $field='water' inside the foreach. This can be done be rethinking the way we build the foreach.
You simply need to make the field value a variable and pass use that rather everywhere the value is needed.
$field = 'Water';
foreach($_POST[$field] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
The advantage of this approach is that if you change your mind and the $_POST key is later called, "liquid" one single line needs to be edited and that is all. Furthermore, if your foreach were part of a function $field could be a function parameter. In a roundabout way, you are actually getting pretty close to some code reuse principles.

Displaying data from a CSV file with multi-dimensional PHP array

I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...
Using this example from php -
<?php
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<div id='car'>".$key.":".$value."</div></br>";
}
}
?>
This is the array I get -
BodyStyle:"Station Wagon"
"DaysInStock":"27"
"Make":"Toyota"
"Model":"Prius v"
"MSRP":"0"
"SellingPrice":"26995"
"StockNumber":"387515"
"Trim":"Three"
"VIN":"JTDZN3EU9E3306528"
"Year" :"2014"
Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?
I have tried this:
print_r ($csv[0]['Make'];
echo $csv[0]['Make'];
Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.
From here how would I strip the quotes and break out each value?
This is the error being thrown -
Invalid argument supplied for foreach() in
Thanks in advance!
foreach($csv as $car){
echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}
alternatively:
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
}
}
alternatively:
echo $csv[0]['Make'];
Try this one :
print_r ($csv[0]['Make']);
Basically the $csv variable is an array, to get its values you have to use the loop function, something like :
foreach ($csv as $data) {
foreach ($data as $index => $value) {
if ($index == "make") {
echo $value;
}
}
}
If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value).
Try it and you'll see :)
PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.
So I figured out that I only need 1 foreach loop like so -
foreach($csv as $car){
$type = $car[0];
$echo $type;
}
Works now and thanks all for the help!

PHP removing elements from array in a foreach loop

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.
if (isset($this->request->post['merge'])) {
$merge_orders = $this->request->post['merge'];
}
$selected_order = min($merge_orders); // Fetch the max value order_id
unset($merge_orders[$selected_order]); // Take it out of the array.
$orders_list = explode(',', $this->request->post['order_id_list']);
$removeKeys = $merge_orders;
foreach($removeKeys as $key) {
unset($orders_list[$key]);
echo $key;
}
echo print_r($orders_list);
The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.
If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.
Try this so that you are getting a key from the foreach loop and not a value
foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

Get names of GET method variables

I have about 5 variables in GET method. They almost always have different names, encoded mostly. How i can get name (not value) of those variables.
example:
$_GET['orchid'] = red;
$_GET['xyc'] = wrack;
and after that, next time i open the page:
$_GET['rose'] = red;
$_GET['gzuy'] = bottle;
Values are not important for now, in this case I need names of variables: "orchid", "xyc" or in second case "rose" and "gzuy".
array_keys($_GET)
For more informations, see the link bellow:
http://php.net/manual/function.array-keys.php
foreach ($_GET as $key=>$value){
echo $key;
}
array_keys() should do the trick:
$keys = array_keys($_GET);
foreach ($_GET as $key => $value) {
//Line below is optional to get around empty values.
if (!empty($value))
echo $key, ' ';
}
The above code will print out all of the set $_GET variables, having file.php?moo will mark moo as set but with a value of nothing. The below snippet will simply return an array just containing the names of the $_GET variables which can then be used in $_GET[$keys[0]] for example to recall its value.
array_keys($_GET);
Docs:
foreach loop
array_keys()

foreach () Error

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

Categories