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{}
User gives a input for label and for key too with the other parameters(Key and Label are just example)
I want to add Key to label only once means only at first execution (first button press - but after that on every button click it should not add; php file loads on every button)after that it should be avoided to add (prepend) (key_valuelabel_value)
So my existing code adds key to label but this fails when if user gives label which has value similar to key.
For example:- key='123' and label='123 test' then my condition fails.
So anyone suggest me on this how can I handle this case ?
This is php, everytime it reloads so counter also failed.
I don't asking why do you need that. Hope this code can helps:
function isKeyInLabel($key, $label) {
$keys = explode(' ', $label);
// remove last element (it's a label)
array_pop($keys);
return in_array($key, $keys);
}
usage example:
// this condition will returns true
if (isKeyInLabel('456', '123 456 789 test')) {
// already exists
}
notice: of course you can't use keys or labels with spaces
UPD:
You'll need another variable, for example:
// of course you need a place where you can save this array
// as possible place you can use session or cookies, or
// whatever you want, here is session usage example
session_start();
// this hash will have keys that already executed
$execKeys = isset($_SESSION['execKeys'])?$_SESSION['execKeys']:array();
// assuming that $execKeys[$label] is an array
if (isset($execKeys[$label]) && in_array($key, $execKeys[$label])) {
// code already executed
} else {
$execKeys[$label] = isset($execKeys[$label])?$execKeys[$label]:array();
$execKeys[$label][] = $key;
// and if you still need it
$label = $key.' '.$label;
}
$_SESSION['execKeys'] = $execKeys;
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.
public function action_adicionar_item()
{
$lista_item_pedido = array();
$x = 0;
if(Session::has('lista_item_pedido'))
{
foreach(Session::get('lista_item_pedido') as $item)
{
$lista_item_pedido[$x] = $item;
$x++;
}
}
$lista_item_pedido[$x] = Input::all();
Session::put('lista_item_pedido', $lista_item_pedido);
}
The first time I ran this method, the session is not created so the if is ignored and it sets the array value and should define the session with name a value but it doesn't.
The second time I call it, the session is created but with no values, what is weird.
Any ideas why on my first run the session is created with the empty array?
Input::all() is returning the correct values.
I have checked the file storage/sessions/ the file is created and the value is set correctly:
s:17:"lista_item_pedido";a:1:{i:0;a:7:{s:2:"id";s:3:"162";s:10:"referencia";s:12:"112233445566";s:9:"descricao";s:6:"Sapato";s:5:"grade";s:14:"Grade 41 ao 46";s:8:"grade_id";s:1:"4";s:5:"valor";s:5:"50.00";s:10:"fornecedor";s:2:"30";}}}s:13:"last_activity";i:1340395110;}
This is created the first time I run the method, so it is created but I can't access it, only when I add two values and in this case, the first is ignored.
Try using $_SESSION instead...
I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.
function addToDiscountArray($item){
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?
Many thanks
The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page.
Try adding session_start() at the beginning of the function.
function addToDiscountArray($item) {
if (!$_SESSION) { // $_SESSION is NULL if session is not started
session_start(); // we need to start the session to populate it
}
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.