I'm kinda lost here.
So here is what i'm trying to do.
I have a session, that's called "test", i have set the session to be an array every time that $_POST['process'] isset.
The $_POST['process'] is containing a integer, that's fetched from a DB Table.
Here's my code:
if(isset($_POST['process']))
{
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
It work's at first time, here's the result:
[test] => Array
(
[0] => 21311
)
I was expecting, that it would create a new key, and assign it to the other value that get's fetched from $_POST['process'] - but instead it just overwrites the 0 key.
What am i doing wrong here?
Kind regards
In your code you're writing $_SESSION['test'] = array(); which is resetting the value of $_SESSION['test'] to an empty array. Therefore it has removed your previous value and have put in your new one.
To fix this check if $_SESSION['test'] is already set, if it's not do $_SESSION['test'] = array();, otherwise just insert new values.
Full example:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
Honestly, this is one precise case where using array_push() is a disadvantage versus its alternative square bracket syntax.
array_push() requires you to declare the empty array in advance; [] will not AND it is functionless AND it is more brief to code.
Furthermore, I am nearly 100% sure that you don't actually want to know the new element count after pushing. The PHP Manual says:
Returns the new number of elements in the array.
...so, if you do want to know the new count, then perhaps rename your variable from $array_merge to $array_size or $array_count or $array_length.
I know I wouldn't want to write an extra condition just to declare an empty variable then use a function to add a new element, especially when it can be done in one line
if(isset($_POST['process'])) {
$_SESSION['test'][] = $_POST['process']; // all done
}
This will work the first time and every time as desired.
Related
Is there a way to execute a code only when my array has a new value passed on in position [0];?
if(?){
print_r(array_values($parcels)[0]);
} else{}
tried multiple statements but all lead to error or invalid. If a new order comes in array[0] gets replaced with that info. So only when that info has changed execute this.. Is this Possible?
You need to store the old value in an other variable to compare it. So you are able to consider if the value has changed.
$oldValue = $parcels[0];
//-------
//Code that eventually changes the array
//-------
if($oldValue != $parcels[0]) {
print_r(array_values($parcels)[0]);
$oldValue = $parcels[0];
} else{}
I ran across some example code that looks like this:
$form['#submit'][] = 'annotate_admin_settings_submit';
Why is there a bracket after ['#submit'] that is empty with nothing inside? What does this imply? Can anyone give me an example? Normally (from my understanding which is probably wrong) is that arrays have keys and in this case the the $form array key '#submit' is equal to 'annotate_admin_settings_submit' but what is the deal with the second set of brackets. I've seen examples where an array might look like:
$form['actions']['#type'] = 'actions';
I know this is a very basic question about php in general but I ran across this question while learning Drupal so hopefully someone in the Drupal community can clarify this question that I'm obsessing over.
When you say $form['actions']['#type'] = 'actions', it assigns a value to $form['actions']['#type'], but when you say $form['#submit'][] = 'annotate_admin_settings_submit', if $form['#submit'] is an array, it appends 'annotate_admin_settings_submit' to the end of it, and if it's empty, it will be an array with one single element that is 'annotate_admin_settings_submit'.
The empty brackets mean that when the string is added to the array, php will automatically generate a key for the entry instead of it being specified in the brackets when populating the array.
So $form['#submit'][] = 'annotate_admin_settings_submit'; is the same thing as $form['#submit'][0] = 'annotate_admin_settings_submit'; if it's the first time you do it.
Next time it will be $form['#submit'][1] = 'annotate_admin_settings_submit';, etc.
The empty bracket adds an auto increment index to an array. The new index will be +1 to the last index.
Please check this example.
$form['#submit'][0] = 'zero';
$form['#submit'][1] = 'One';
$form['#submit'][] = 'Two'; // this will be considered as $form['#submit'][2] = 'Two';
$form['#submit'][4] = 'Four';
$form['#submit'][] = 'Four'; //this will be considered as $form['#submit'][5] = 'Four'; since its adds 4(last index)+1
This is honestly the most finicky and inept language I've ever coded in. I'll be glad when this project is good and over with.
In any case I have to us PHP so here's my question.
I have an Array named $form_data as such:
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'allinc_insur',
'allinc_insur_opt1',
'allinc_single_date_go',
'allinc_single_date_ba',
'allinc_insur_opt2',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'cancel_insur',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'visitor_insur',
'country_select',
'visitor_supervisa',
'visitor_supervisa_date_go',
'visitor_supervisa_date_ba',
'visitor_student',
'visitor_student_date_go',
'visitor_student_date_ba',
'visitor_xpat',
'visitor_xpat_date_go',
'visitor_xpat_date_ba',
'txtApp1Name',
'txtApp2Name',
'txtApp1DOB',
'txtApp2DOB',
'txtApp1Add',
'txtApp1City',
'selprov',
'txtApp1Postal',
'txtApp1Phone',
'txtApp1Ext',
'txtApp1Email',
'conpref', );
These are the names of name="" fields on an HTML form. I have verified that ALL names exist and have a default value of '' using var_dump($_POST).
What I want to do is very simple, using the $form_data as reference do this:
create a new array called $out_data which can handle the data to display on a regurgitated form.
The structure of $out_data is simple the key will be the name of the element from the other array $out_data[txtApp1Name] for example, and then the value of that key will be the value.
Now what I want is to first check to see if every name="" is set or not, to eliminate errors and verify the data. Then regardless of whether it is set or not, create its placeholder in the $out_data array.
So if $_POST[$form_data[1]] (name is 'trav_emer_single') is not set create an entry in $out_data that looks like this $out_data([trav_emer_single] => "NO DATA")
If $_POST[$form_data[1]] (name is 'trav_emer_single') is set create and entry in $out_data that looks like this: $out_data([trav_emer_single] => "whatever the user typed in")
I have tried this code:
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(!isset($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = "NO_DATA";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
Now this code technically is working, it is going through the array and assigning values, but it is not doing so properly.
I have hit submit on the form with NOTHING entered. Therefore every item should say "NO_DATA" on my regurgitated output (for user review), however only some items are saying it. All items I have confirmed have name="" and match the array, and have nothing entered in them. Why is "NO_DATA" not being assigned to every item in the array?
Also of note, if I fill in the form completely $out_data is fully and correctly populated. What is the problem with !isset? I've tried doing $_POST[$form_data[$i]] == '' which does put no_data in every instance of no data, however it throws an 'undefined index' warning for every single item on the page whether I write something in the box or not.
Really I just want to know WTF is going on, the dead line for this project is closing fast and EVERY step of the PHP gives me grief.
As far as I can tell by reading around my code is valid, but refuses to execute as advertised.
If you need more code samples please ask.
Really befuddled here, nothing works without an error, help please.
Thanks
-Sean
Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.
I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.
$out_data = array();
foreach ($form_data as $key) {
if(empty($_POST[$key])) {
$out_data[$key] = "NO_DATA";
}
else {
$out_data[$key] = $_POST[$key];
}
}
PHP's isset returns TRUE unless the variable is undefined or it is NULL. The empty string "" does not cause it to return FALSE. empty() will do exactly what you need, though.
http://php.net/manual/en/function.isset.php
isset() will return FALSE if testing a variable that has been set to
NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP
NULL constant.
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.
OK so I'm making something to do some data mining but I do changes to an array (by overwritting previous array values) in a loop and they show that they've been changed but once I get outside of a greater loop the values change back to their original values.
Probably easier to give an example:
It starts off like this, turning a bunch of the parts of the array into the word "MATCH".
Now if I was to immediately dump the values of the array it would show that some values have changed to "MATCH" (ie, right after changing the value I would echo the array slot and it would show it's value to be "MATCH") However after I get outside the loop the array changes back to it's original contents
Here is a compressed version of the code:
//i've got this big loop for doing the main work
do {
//Set dat ticker
$q = 0;
// Run through entire previous scrape array to check for matches and mark them as unchanged
do {
if ($itemTitle[$i] == $prodURLS[$q]) {
$prodURLS[$q] = "MATCH";
echo "When the value is printing immediately it shows that it's changed: ".$prodURLS[$q]."<br>";
}
$q++;
} while ($q < $urlArraySize);
$i++;
} while ($i < $itemtitleArraySize);
//If I were to try to print the variable down here it would be reverted to like it was before I changed it to "MATCH"
print_r($prodURLS);
From running your code, setting the variables as follow, it works for me:
$prodURLS = array('a','b','c');
$itemTitle = array('a');
$urlArraySize = count($prodURLS);
$itemtitleArraySize = count($itemTitle);
$i = 0;
My only recommendations with only this amount of information, are:
To provide more context information, as madth3 suggests.
To check the scope in which you are setting/checking values. You may need the & operator to pass variables by reference, or the global keyword to use global variables.
To use the foreach loop, it will make your code smaller and easier to read. Also you won't need to count the size of the arrays and will have other advantages, e.g. in the use of associative arrays. Again, be careful about the use of variables by reference. For example:
foreach ($itemTitle as $item) {
foreach ($prodURLS as &$prod) {
if ($item == $prod) {
$prod = 'MATCH';
}
}
}
unset($prod); //Unset variable set by reference if you are going to use it later on!
Also, you may find useful some of the php array functions like array_walk. Check out the PHP Manual on the array functions reference.
Really, there isn't a lot that can be said from just the code you provided.
Good luck.
I have been working with C# so this is quite strange for me:
while($variable=mysql_fetch_assoc)
{ $X=$variable['A'];
$Y=$variable['B'];
}
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
I have not been able to look up in PHP manual how it works. I guess that in each loop it advances to next element of assoc.array. But what is this generally called in PHP? I am just not used to see '=' in loop condition.
Assignment in PHP is an expression that returns the value that was assigned. If a row was retrieved then the result will be non-false, which will allow the loop to continue.
mysql_fetch_assoc() (and its related functions) advance $result's internal pointer every time it gets called. So $variable will be assigned a new row array every time the while condition is checked. After the last row is returned, mysql_fetch_assoc() can't advance the internal pointer anymore, so the next attempt to call it will return false. Once $variable becomes false, the condition is no longer satisfied and the loop exits.
In PHP (also JavaScript et al), a condition is true as long as it doesn't evaluate to either zero, an empty string, NULL or false. It doesn't have to evaluate to a boolean value. That's why such a loop works.
EDIT:
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
Yes, they'll be reassigned with the new values from each new row that is fetched.
Perhaps looking at the code like this would be useful:
while (($variable = mysql_fetch_assoc($result)) == true) {
// loops until the fetch function returns false (no more rows)
// $variable will have be an associative array containing the 'next' row from the recordset in $result
}
It's a shorthand way of doing this:
$variable = mysql_fetch_assoc();
while ($variable) {
// loop
$variable = mysql_fetch_assoc();
}
It means something like "until you can mysql_fetch_assoc() an element from the variable you pass to that function, then do the body of the while.
It returns an array if it can find an element, FALSE otherwise, so you can exit the loop.
It's just short form of this code:
$variable = mysql_fetch_assoc($res);
while($variable != FALSE) {
// do something
$variable = mysql_fetch_assoc($res);
}