How to use a foreach loop with var_export? - php

I have a form with some checkboxes in Drupal and I need to get the checked boxes to add them to a database. To get the values in the checkboxes I use var_export which returns an array indicating if the checkbox has been checked. After I have this array store in a variable I do this:
$checked = array();
if(is_array($data) {
foreach($data as &$value) {
if($value != 0) { //the checkbox was checked
$checked[] = $value;
}
}
However, when I print out the variable $checked there is nothing stored in it. What am I doing wrong?

The normal way to do this in Drupal would be:
$checked = array_filter($form_state['values']['name_of_checkboxes_element']);
That will give you an array of all the values selected in your checkbox element, assuming you're running this code in the submit/validate handler for the form.
Also I should mention the Devel module, it has a wonderful function called dpm() which prints the value of any variable to the messages area in a hierarchical format that you can navigate through easily.

Related

PHP check for values before the loop to check

I have a JSON multi-dimensional array of products from Shopify that I am looping through. Each product has 3 options and each option can have infinite numbers of values.
For example:
Lamp (product)
Glass Finish (option)
Clear (value)
Smoke (value)
Metal Finish (option)
Polished Chrome (value)
Drop (option)
600mm (value)
800mm (value)
Within the loop I am creating rows within a 'repeater' field in a CMS (one for each option and then a repeater within each option for each value).
This is all fine BUT I want to do a few checks as the array of products is cached to every 30 minutes so if the cache was updated and either an option was removed or a value to that option was added then it should update.
I have my first check in place (loop through all the existing repeater options that have been added, before doing anything, and if an option already exists then skip it (and thus not creating multiple of the same options).
What I need to do is to check each of the values to see if any new ones have been added. I can write the code to actually add the value to the repeater field but I am unsure how to check as by this point, if the option already exists, it skips over.
Any thoughts?
foreach($product['options'] as $option) {
foreach($p->shop_product_options as $options) {
// If this option already exists... then skip the parent loop on this product
if ($options->global_text == $option['name']) {
continue 2;
}
}
$options = $p->shop_product_options->getNew();
$options->of(false);
$options->global_text = $option['name'];
$options->save();
$p->shop_product_options->add($options);
foreach($option['values'] as $o) {
$values = $options->shop_product_options_option->getNew();
$values->of(false);
$values->global_text = $o;
$values->save();
$options->save();
$options->shop_product_options_option->add($values);
}
$options->save();
}
Still not sure I am completely understanding what you are after but it sounds like you need something like this :
foreach($product['options'] as $option) {
$optionNames = array_column($options, 'name');
$options = $p->shop_product_options->getNew();
foreach($option['values'] as $o) {
$values = $options->shop_product_options_option->getNew();
if($values->global_text === $o && in_array($option->global_text, $optionNames, true)) {
continue 2;
}
$values->of(false);
$values->global_text = $o;
$values->save();
$options->shop_product_options_option->add($values);
}
$options->of(false);
$options->global_text = $option['name'];
$p->shop_product_options->add($options);
$options->save();
}
array_column will create an array getting all the values of a multidimensional array when the key is name, and then the if statement will look for a combination of name and value.
And since the saving logic for the option is below the loop for the values,
it will check the cache before saving anything, this might not be a copy/paste answer, i'm just giving you some logic to work with

PHP array of arrays. Checkboxes to be ticked depending on inner array values

I have arrays of Strings(that are each a combination of numbers "1" to "20") inside another array in PHP. I want to pre-tick the corresponding checkboxes (1 - 20) for each of my pages (these start at 0 and go on for potentially very many).This way the user can go to a page and see which boxes have been selected before. For example:
Array [0] is {1, 2, 4} so these checkboxes should be checked when the user arrives at page 0. This is what I have so far to try and get the values of the inner array:
foreach ($categoriesArr as $val) {
if (is_array($val)) {
foreach ($val as $innerVal) {
// See which checkboxes are checked.
if ($innerVal === "1") {
$cb1 = true;
} else {
$cb1 = false;
}
}
}
}
I know I can use <?php if ($cb1) echo "checked" ?> in the checkbox HTML to show it as ticked.This is ok but it obviously loops through all the arrays and $cb1 will eventually end up as whatever the last arrays value is. Should I introduce yet another array to store each individual pages checkbox values in? I am potentially dealing with thousands of entries so would like to keep any extra assignments to a minimum.
I would suggest to have variable that holds page's index, and then you just include this into each checkbox:
<?php if(is_array($categoriesArr[$pageIndexVariable]) && $categoriesArr[$pageIndexVariable][$checkboxNameOrIdOrwhatever]) echo "checked" ?>

PHP post all form inputs without creating variables for each

Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.

How can I check if a php array's keys all have values and none are blank or unset

I create a php array on the fly like below in php, which is then json_encoded and sent back to the ajax script that requested it.
$myarr['key_a'] = 'a';
$myarr['key_b'] = 'b';
$myarr['key_c'] = 'c';
Before I do the json_encode, since the values for this come from a database, is there someway I can check if all values are set and none are blank or unset without having to check each key individually?
if (count($myarr) != count(array_filter($myarr))) {
// Oops, empty values
}
//$arr is your array contains values from database
$newArr = array();
foreach($arr as $key => $val) {
if(trim($val) != ''){
$newArr[$key] = $val;
}
}
json_encode($newArr);
If you don't want to go running around and checking each key individually (by using foreach), you should be making sure that the generated array is already checked on creation.
Adding a if(empty($value)) { // Do stuff } might fix your problems at its core.

Foreach value from POST from form

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need

Categories