How can I rewrite this piece of php script to not use the deprecated function 'each' anymore in the 'if' statement ?
if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
{
...
}
Many thx in adv. for you input !
V.
[EDIT]. This if statement is not in a loop. It's part of an larger block:
if (!empty($_basic_auth_header))
{
....
}
else if (!empty($_basic_auth_realm) && isset($_auth_creds[$_basic_auth_realm]))
{
....
}
else if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
{
....
}
$_basic_auth_realm, $_basic_auth_header are strings
$_auth_creds is an array
I don't really understand how this 'if' statement works. I only attempt to update the script which returns warnings when executed. It is used as a php proxy on my NAS as was written by Abdullah Arif: https://github.com/emersion/phproxy
Use your own variable to keep track of the current index in the array, rather than depending on the internal state of the array.
$auth_creds_index = 0;
...
else if (list($_basic_auth_realm, $_basic_auth_header) = $_auth_creds[$auth_creds_index++])
Each place where you currently use each($_auth_creds) should use $_auth_creds[$auth_creds_index++], they'll get successive elements of the array.
If you reassign the variable with a new array, you need to reset the variable back to 0.
You could also define a class wrapper for the array that automates all this.
Related
[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']
Before looping through a variable (supposed to be an array)
I would make the following test:
if(
!empty($arrJobs) &&
is_array($arrJobs) &&
count($arrJobs)
){
foreach ($arrJobs as $item) {
//loop tasks
}
}
I've seen also using if(sizeof($arrJobs)>0) but in case $arrJobs isa integer (I can't trust the input) it would be through and I will try looping through a integer...weird.
Is there a more concise and comprehensive way to perform this test before looping through the array?
It is IMPORTANT to check if you're looping an ARRAY to FOREACH or else PHP will give you errors ... FOREACH expects parameter to be ARRAY..
You can use IS_ARRAY .. I believe that would be enough.
But checking it if empty would be VERY GOOD Practice... I'm using COUNT() to check if an ARRAY is empty.
You don't need to check anything but is_array: if it's empty, PHP simply won't loop.
Moreover a suggestion: if those if had sense (not that case, but is helpful for this explanation) you should split with "early exit" (as coding style because it improves readability)
if (empty($arrJobs)) {
return;
}
if (!is_array($arrJobs)) {
return;
}
if (count($arrJobs)) {
return;
}
I will be reusing a Drupal db_query result set unpacking function many, many times in my code for a variety of different queries - I am using O-O and as such I want to reuse it and be as 'DRY' as possible.
Therefore I have tried to strip it down to the most generic functions so that as long as the $columns supplied match the columns used in the query and similarly in the $resultset, I can loop and assign values to keys, as is shown, and return a $rows[].
I've not yet come across the issue of trying to use a variable's value as a variable name (the $key), if it's just something I should avoid entirely, please say.
foreach($this->resultSet as $aRecord) {
$c = 0;
while (isset($this->columns[$c])) {
$value = $this->columns[$c];
$rows[$i] = array(
$key[$this->columns[$c]] => $aRecord->$value,
);
$c++;
}
$i++;
}
I've read through the following and am beginning to think this is just knowledge I'm missing in my PHP experience so far.
Can I use a generated variable name in PHP?
PHP use function return value as array
https://wiki.php.net/rfc/functionarraydereferencing
It felt wrong, and someone once told me that if you have to start writing complex functions in PHP you've probably missed an available function PHP already offers.. so true... thanks to (at the time of writing...) 'MrCode' for this suggestion.
$this->sql = "SELECT foo, bar FROM foobar";
$this->result = db_query($this->sql);
if ($this->result->rowCount() > 0) {
while ($row = $this->result->fetchAssoc()) {
$this->resultArray[] = $row;
}
}
I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST. I'm currently using:
while(list($key_member,$member)=each($_POST['member_ids'])
&& list($key_amount,$amount)=each($_POST['payment_amounts']))
{
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
If I use one list() on either array it will print the info for that particular item. However, if I attempt to use multiple list() commands in the while, only the last list()ed item gets filled properly. Is list() doing some trickery in the background that's preventing it from working in a while loop?
Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to
What am I doing wrong, and/or what is "broken" with list()?
bug? dunno.
here's a workaround.
while(list($key_member,$member)=each($_POST['member_ids'])){
list($key_amount,$amount)=each($_POST['payment_amounts']);
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:
$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);
$mi = 0;
$am = 0;
while(1) {
...
$mi++
$am++;
if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
break;
}
}
&& is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.
The code below is just a sample of the format I have
isset($_GET['ids'])?$ids=$_GET['ids']:null;
isset($_POST['idc'])?$idc=$_POST['idc']:null;
function ShowCart()
{
$que = "SELECT
FROM
cart
LEFT OUTER JOIN ...
ON ...
LEFT OUTER JOIN... ON...
WHERE ";
$result = mysql_query($que);
while(){
if (isset($ids)) {
display something
for (){
if(){
} // end of if inside the for loop
}// end of for loop
}
elseif($idc && $ids=null) {
display something different
}
else{
display nothing has passed
}
}//end of while loop
}//end of showcart(); function
that's the formatting above I wonder why the if and elseif are not getting the isset() as the if and elseif argument.
I have debug the through the whole code and the print_r of GET and POST has values through the whole code.
print_r($_POST);
print_r($_GET);
Jona, if you'd ever bother to properly format your code, you'd see that the 'else' in question is WITHIN A FUNCTION, and you're defining $ids and $idc OUTSIDE THE FUNCTION. Remember, in PHP, global variables (except the super-globals, such as $_GET, $_POST, etc...) are not visible within functions unless you explicity define them as globals within the function.
Add global $idc, $idc; as the first line in the function definition and your if() will start working correctly.
Followup:
Your code is still hideously formatted, and very wonky. Take this:
isset($_GET['ids'])?$ids=$_GET['ids']:null;
You're using a trinary operator, but not assigning its results anywhere, and using the 'true' condition to do an assignment. This is an ugly hack. It should be written like this:
$ids = isset($_GET['ids']) ? $_GET['ids'] : null;
This way $ids will be set to null if there is no $_GET['ids']. Which brings up the fact that you're assigning a null instead of some other default value. If there really was no $_GET['ids'], then this:
$idx = $_GET['ids'];
would work identically, as PHP will automatically assign a null in situations where the right-hand-side doesn't exist. Of course, you still have to sanitize this value, since you're using it in an SQL query later on. Leaving it like this will just invite SQL injection attacks and all kinds of other abuses.
Beyond that, you're still creating $ids and $idc OUTSIDE of your ShowCart() function. As such, $ids and $idc within the function will be automatically be created with null values, since you've not declared them to be global. I think by now it's obvious you have no idea what this means, so try out this piece of code:
<?php
$var = 'Here I am!';
function showVar() {
echo "Within showVar(), var is set to: $var\n";
}
function workingShowVar() {
global $var;
echo "Within workingShowVar(), var is equal to: $var\n";
}
showVar();
workingShowVar();
If you copy/paste this code, run it, you'll see the following output:
Within showVar(), var is set to:
Within workingShowVar(), var is set to: Here I am!
Notice that both functions are identical, except for the global declaration. If you can figure out the difference, then you'll realize you need to re-write your ShowCart() function as follows:
function ShowCart() {
global $ids, $idc;
// rest of your code here
}
Well the code you've posted is sound, so it's probably a problem with the variables getting to that script in the first place. Are you sure those variables are defined in the GET string?
Dump out the contents of it to make sure:
print_r($_GET);
Try this:
$ids= isset($_GET['ids'])?intval($_GET['ids']):null;
$idc= isset($_GET['idc'])?intval($_GET['idc']):null;
if (isset($ids)) {
//display something
}
elseif(isset($idc)) {
//display something different
}
else
{
//display nothing has passed
}
I tested your script above,it works as expected.Maybe you should check whether the link is correct or not.