Handling Multiple Input : Array vs Loop, Which Is Low Resource Consuming? - php

I have multiple input tag submitted from previous page, say step1.php like this :
<input type="hidden" name="block01" value="001"/>
<input type="hidden" name="block02" value="012"/>
<input type="hidden" name="block03" value="002"/>
<input type="hidden" name="block04" value="005"/>
<input type="hidden" name="block05" value="008"/>
<input type="hidden" name="block06" value="015"/>
now I want to process those inputs in the step2.php and I have 2 options to do it, either using Array or Loop.
If I'm using array, those inputs will be appended like this :
<?php
$stack = array(""); //empty array declared
// I assume I have some codes here to 'catch' those inputs and put it as array_push
array_push($stack, "001", "012", "002", "005", "008", "015");
print_r($stack);
?>
compare to array, I have this LOOP option too :
<?php
$i = 1;
$x = 'block0'.$i;
$webBlock = $_POST[$x];
while (!empty($webBlock)){
$x = 'block0'.$i;
$webBlock = $_POST[$x];
echo $webBlock . "<br />";
$i++;
}
?>
both are solutions of my problem on step2.php. I just need your opinion which is more less memory / cpu consuming? that's all...
thanks!

In first case, you are using array_push() and print_r(). The first function uses a loop to push arguments passed onto a stack. The second function that is print_r() also uses a loop to print all the values of the array. So, basically you are running loop twice to do the task.
Where as in second case, you have written a code to handle both things at once. So, this method just needs to loop once. Moreover, looking into the working of print_r() and echo, if you run echo X times and use print_r() to print X values, the echo is bit faster than print_r. Read php documentation for more info about all these function.
So, the second way is better.

Related

Passing all values into one variable then split them [duplicate]

This question already has answers here:
Passing an array using an HTML form hidden element
(8 answers)
Closed 3 years ago.
Hi so for the website I am designing I have been asked to use mal's eCommerce for the payment gateway. I have been trying to set up the remote call function they have so that once a purchase has been made it will make a call back to my website to run a script and sen email confirmation of their order.
This however has proved extremely frustrating as the session variables I have stored do not get passed through with the remote call, only certain values that they allow.
I tried storing them all in an array and putting them in one of the values I can change called sd:
$cart =array($_SESSION["date"], $_SESSION["name"], $_SESSION["email"], $_SESSION["number"], $_SESSION["address"], $_SESSION["town"], $_SESSION["postcode"],
$_SESSION["county"], $_SESSION["cake_type"], $_SESSION["collection"], $_SESSION["icingColour"], $_SESSION["trimColour"], $_SESSION["filling"], $_SESSION["wording"],
$_SESSION["cakePhoto"], $_SESSION["price"], $_SESSION["photo"] );
<input type="hidden" name="sd" value="<?php echo $cart?>">
Then in my script I tried:
$result = $_POST['sd'];
echo $result[0];
to test it
but the remote call just passed the value as "Array" so echo $result[0] just returned "A", the values was just passed as Array and none of the values in the array got passed with it.
So now I'm trying to store all my session variables in the sd value like this:
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $val;}?>">
and then I tested it by doing on my script:
$result = $_POST['sd'];
echo $result;
Now this does pass all the values but obviously just as one big value, is there a way I can split them up? Is there a better way with the array I haven't thought of? Any advice would be greatly appreciated because I'm at a complete loss
Edit:
Forgot to add this part:
So after the array has been split I would need to stored the values separately so something like:
$name = first value
$email = second value etc
try changing <input type="hidden" name="sd" value="<?php echo $cart?> to
<input type="hidden" name="sd[]" value="<?php echo $cart?>
or use serialize() then unserialize() the result.
Refer to Passing an array using an HTML form hidden element
You can use php implode and explode function.
The first part is implode.
We use ; as implode delimeter which joins array elements as single string using that delimeter.
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $val.';';}?>">
Explode converts that string to array again using the delimeter we passed.
foreach (explode(';', $_REQUEST["sd"]) as $key) {
echo $key;
echo "<br>";
}
Update : Try This
<input type="hidden" name="sd" value="<?php foreach ($_SESSION as $key=>$val) { echo $key.';'.$val.';;';}?>">
Explode converts that string to array again using the delimeter we passed.
foreach (explode(';;', $_REQUEST["sd"]) as $key) {
echo explode(';', $key)[0];
echo " = " ;
echo explode(';', $key)[1];
echo "<br>";
}

Calling an array element inside another array

I think this is a naive question, but I can't find the proper syntax.
I have this code:
for ($i=1; $i<count($MyArray1); $i++){
$element=$MyArray1[$i];
$foo = $AnotherArray[$element];
echo $foo;
}
How can I skip the second line? I mean, the third line to be something like
$foo = $AnotherArray[$MyArray1[$i]];
for ($i=1; $i<count($MyArray1); $i++){
echo $AnotherArray[$MyArray1[$i]];
}
You can skip a fair amount of that code to make it a bit clearer. Firstly use foreach instead of for as it's a much more reliable way of iterating over arrays. Secondly I've broken down what you're trying to do, to simplify how you're getting it. Basically using the values of one array as the keys of another. So how to do it in three lines:
foreach(array_intersect_key($AnotherArray, array_flip($MyArray1)) as $value) {
echo $value;
}
This is using the excellent array_intersect_key method to grab all of the values from $AnotherArray with keys that match in the other array. As you want to use the values, we use array_flip to swap the keys and values, then just loop over the result and echo it.

How to send array with various submit buttons?

Can you send an array with various values in html? I would like to send different array values with various different submit buttons all within one <form> element.
Here is what I am doing currently. It works so I'm not having a problem, but I couldn't find any documentation for anything similar and I am really curious if theres another way.
Button with my *psuedo*array
<input type="submit" name="form_action" value="action:new_business,id:0">
Decode function:
$action = explode(',', $_POST['form_action']);
$new = array();
foreach ($action as $v) {
$t = explode(':',$v);
$new[$t[0]] = $t[1];
}
print_r($new);
And the results:
Array ( [action] => new_business [id] => 0 )
Of course, this works, so I'm really just curious whether there's a built in solution already.
The desired simplicity:
<input type="submit" name="array" value="array('0'=>'foo','1'=>'bar')">
print_r($_POST['array]);
Array ( [0] => foo [1] => bar )
Edit: I know how to send arrays with html, but that was not my question. If I use hidden inputs, they get sent regardless of which submit button I click, there will be multiple submit buttons contained in one <form> element, and I need to know which was clicked and what action it is going to be used for. Sorry if that was unclear but I don't think I deserve downvotes either way...
Try this:
<input type="hidden" name="form_action[action]" value="new_business" />
<input type="hidden" name="form_action[id]" value="0" />
Inputs with names of the form name[key] will be condensed into an array. This also applies to name[], which will become elements of an indexed array.
I know the question is old. I still like to answer this, as I am implementing currently something similar.
You can indeed write your statement and turn it into a valid context. By implementing:
if(isset($_POST['array'])){
eval('$my = '.$_POST['array'].';');
print_r($my);
}
you concatenate your POST to a valid php expression in string format and evaluate it. This however is very dangerous because it allows execution of any code inside without any verification. You MUST NOT use this in a public environment because anyone can easily modify the string being send by the button.
The best solution in terms of safety and efficiency is really to send a csv format:
<input type="submit" name="array" value="array('0','foo','1','bar')">
in php do:
$my_assoc = array();
if(isset($_POST['action'])){
$my = explode(",",filter_input(INPUT_POST, 'action' , FILTER_SANITIZE_STRING));
for($i = 0, $num = count($my); $i < $num; $i+=2){
$my_assoc[$my[$i]] = $my[$i+1];
}
print_r($my_assoc);
}
The explode function is linear in complexity and has no large impact. By filtering the csv string, you can also make sure to have no unwanted characters in it (never trust incoming data). You can then either keep the indexed array ($my) and treat every two values as (psydo) key-value pair or turn it into an associative array ($my_assoc).

moving a numbered amount of named items from one array into another

I'm not exactly sure how the logic would work on this. My brain is fried and i cant think clearly.
I am handling some POST data, and one of the fields in this array is a quantity string. I can read this string and determine if there are more than 1 widgets that need handled.
if($quantity <= 1){ //$_POST[widget1] }
Now say there are 4 widgets. The quantity field would reflect this number, but how would i loop through them and assign them to a new array themselves?
$_POST[widget1], $_POST[widget2], $_POST[widget3], $_POST[widget4]
How do i take that quantity number, and use it to grab that many and those specific named items from the post array, using some kind of wild card or prefix or something? I dont know if this is a for, or while, or what kind of operation. How do I loop through $_POST['widget*X*'], where X is my quantity number?
The end result is im looking to have an array structured like this:
$widgets[data1]
$widgets[data2]
$widgets[data3]
$widgets[data4]
Using a for loop, you can access the $_POST keys with a variable, as in $_POST["widget$i"]
$widgets = array();
for ($i=1; $i<=$quantity; $i++) {
// Append onto an array
$widgets[] = $_POST["widget$i"];
}
However, a better long-term solution would be to change the HTML form such that it passes an array back to PHP in the first place by adding [] to the form input's name attribute:
<input type='text' name='widgets[]' id='widget1' value='widget1' />
<input type='text' name='widgets[]' id='widget2' value='widget2' />
<input type='text' name='widgets[]' id='widget3' value='widget3' />
Accessed in PHP via $_POST['widgets'], already an array!
var_dump($_POST['widgets']);
Iterate over the number of items, at least over one (as you describe it):
$widgets = array();
foreach (range(1, max(1, $quantity)) as $item)
{
$name = sprintf('widget%d', $item);
$data = sprintf('data%d', $item);
$widget = $_POST[$name];
// do whatever you need to do with that $widget.
$widgets[$data] = $widget;
}

in_array giving Warning Message

All,
I have the following code:
$qry = "Select * from vendor_options order by vendor_option_name ASC";
$result = mysql_query($qry);
while($resultset = mysql_fetch_array($result)){
if(isset($_SESSION['pav_choosen_vendor_categories'])){
for($z=0;$z<$_SESSION['pav_choosen_vendor_categories'];$z++){
$sVendorId = $_SESSION['pav_vendor_categories_' . $z];
if($sVendorId==$resultset['vendor_option_id']){
$vendor_cats_choosen[] = $sVendorId;
}
}
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
}
}
I'm trying to check to see if the value returned in the mysql_fetch_array is already in my array. Say the first value it finds in the array is in the fourth iteration of the while loop. I'll get the following error:
Warning: in_array() expects parameter 2 to be array, null
Once it gets to a value that is in the array the rest of them work fine. Why does itgive an error for the first couple? Thanks.
It looks like you have not initialized $vendor_cats_chosen to be an array, and so if the condition if($sVendorId==$resultset['vendor_option_id']) is not true, no elements will be appended to it, turning it implicitly into an array.
Initialize it before the while loop. You should just about always initialize arrays before use.
// Initialize the array
$vendor_cats_chosen = array();
while($resultset = mysql_fetch_array($result)){
....
Now, when your in_array() statement executes, the array may be empty, but will be a valid array.
// $vendor_cats_chosen might be an empty array, or may have elements.
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
The problem is that your array not always creates. To fix this issue just add
$vendor_cats_choosen = array();
somewhere before while in your code.
You only ever populate the array $vendor_cats_choosen inside an if statement, which means it can potentially contain no values. You also do not declare it before you start the loop which populates it - which you should do anyway, because adding a value to an undeclared array will emit an E_NOTICE.
Add the line
$vendor_cats_choosen = array();
...at the top of the script and the error will disappear. If you think this array should contain values, you may need to examine the logic in your if statement.
In order to eliminate the warning message, two approaches can be followed:
1) use of # before the statement which is generating the warning message ( However, this is not an advisable engineering approach )
2) prior to using the array object, it can be filtered out in an if-else.
For example, in your case, you can add this line
if( $vendor_cats_choosen ){
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
} ?>

Categories