PHP - Incorrect use of static variable? - php

I'm trying to make a simple code in PHP in order to decide when I can make a query.
My code looks like this :
$status = shell_exec("/usr/local/bin/gpio -g read 17");
static $status_lpv = 0;
if ($status == 1 )
{
if($status_lpv == 0)
{
$status_lpv = 1;
echo " do the job ";
}
}
if($status == 0 )
{
if($status_lpv == 1 )
{
$status_lpv = 0;
echo "do another job ";
}
}
My variable $status_lpv is always 0. What I'm doing wrong ?

Try to wrap the code into function (if not there yet) and call the function

You cannot store status between http calls in a (static) variable.
You need persistent storage, locking etc. (eg. try a database)

Related

I receive the following error : " Can't use method return value in write context "

<?php
include("Emp.php");
$Email = $_GET["id"];
User::FileLoader();
$content = "";
foreach (User::$userlist as $user) {
if ($user->get_Email() == $Email) {
if ($user->get_State() == 1) {
$user->set_State() = 0;
}
else if ($user->get_State() == 0) {
$user->set_State() = 1;
}
}
}
header("location:liste.php");
The error message may be a little obtuse, but it's not that hard to understand. The return value of a function call is just that -- a value. Unlike a variable, it is not backed by persistent storage, so you cannot write to it by, for example, using it as the left-hand operand of an assignment.
Thus, both this ...
$user->set_State() = 0;
... and this ...
$user->set_State() = 1;
... are wrong.
You have not presented your User class to inform an answer, but surely the set_State() method expects you to specify the new state via an argument. For example,
$user->set_State(0);

Advice in design about Control Structure else if, switch o a better way?

I made the script to do what is expected, so it work ok but there must be a more elegant way to achieve the same result. I know that using switch will make it look nicer but not sure if the result will be the same as the 'default:' behavior:
This is the section of the script i want to refactor:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
// Here i call a function that do a mysql query and
// return the user active tasks
$result = tasks($deadline,$user);
$row_task = mysql_fetch_array($result);
// HERE IS THE UGLY PART <<<<<----------------
// the array will return a list of tasks where this current
// users involved, in some cases it may show active tasks
// for other users as the same task may be divided between
// users, like i start the task and you continue it, so for
// the records, user 1 and 2 are involved in the same task.
// The elseif conditions are to extract the info related
// to the current $user so if no condition apply i need
// to change function to return only unnasigned tasks.
// so the i need the first section of the elseif with the
// same conditions of the second section, that is where i
// actually take actions, just to be able to change of
// change of function in case no condition apply and insert
// tasks that are unassigned.
if ($row_task['condition1'] == 1 && etc...) {
} else if ($row_task['condition2'] == 1 && etc...) {
} else if ($row_task['condition3'] == 1 && etc...) {
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
// in case no condition found i change function
// and overwrite the variables
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition3'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
echo 'nothing to insert</br>';
}
}
}
Basically i run the else if block twice just to be able to change of function in case nothing is found in the first loop and be able to allocate records unassigned.
I haven't changed the functionality of your code, but this is definitely a lot cleaner.
The main problem was that your logic for your if/else statements was confused. When you're writing:
if($a == 1){ } else if($b == 1){ } else if($c == 1){ }else{ //do something }
You're saying If a is 1 do nothing, if b is 1 do nothing, if c is 1 do nothing, but if all of those did nothing, do something when you can just say if a is not 1 and b is not 1 and c is not 1, do something.
I wasn't too sure on your second if statements, but generally it's not good to have an if else with no body within it. However, if the "insert into database" comment does the same thing, you can merge the 3 if statements that do the same code.
I hope i've cleared a few things up for you.
Here's what I ended up with:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
$result = tasks($deadline, $user);
$row_task = mysql_fetch_array($result);
if (!($row_task['condition1'] == 1 || $row_task['condition2'] == 1 || $row_task['condition3'] == 1 || $row_task['condition4'] == 1)) {
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1) {
// insert into database
} else if ($row_task['condition3'] == 1) {
// insert into database
} else if ($row_task['condition4'] == 1) {
} else {
echo 'nothing to insert</br>';
}
}
}

Calculate Library Fine (PHP)

So, here is the question (https://www.hackerrank.com/challenges/library-fine) I am trying to solve. To solve this, I created a simple function calculateFine and set the conditions to calculate the fine. What's the problem, then? Well, when I run the code on my machine, everything seems fine, but hackerrank won't accept the code. I am new to PHP and concept of functions was a bit confusing for me, but I tried. Below is my code:
<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$_a = explode(" ",fgets($_fp));
$_b = explode(" ",fgets($_fp));
// Initialising variable
$_fine = "";
// Calling Function
calculateFine($_a,$_b);
// Defining Function
function calculateFine($actualDate, $returnDate)
{
// Checking various conditions
if ($actualDate[0] <= $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_fine = 0;
echo $_fine;
}
elseif($actualDate[0] > $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[0] - $returnDate[0];
$_fine = 15*$_late;
echo $_fine;
}
elseif($actualDate[1] > $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[1] - $returnDate[1];
$_fine = 500*$_late;
echo $_fine;
}
elseif($actualDate[2] > $returnDate[2])
{
$_fine = 10000;
echo $_fine;
}
else
{
$_fine = 0;
echo $fine; // Updated (This is the undefined variable causing error )
}
}
?>
It seems there's a newline in $actualDate[2]. So if you trim it you'll get the right answer:
trim($actualDate[2])
But would be better to trim it here already:
$_a = explode(" ",trim(fgets($_fp)));
$_b = explode(" ",trim(fgets($_fp)));
I got it, sorry for the carelessness. The last echo is $fine instead of $_fine. That's why the condition was not matching with some of the test cases. Thankyou.

if statement when NULL (PHP)

I want to have if the variable = null then he makes it to 1.
if the variable exist do nothing and dont make it again to 1.
i got this code:
if (isset($_POST["register"])) {
if(!$l_NextPage){
$l_NextPage = 1;
echo "helaas" . "</br>";
}
if($l_NextPage == 1){
echo "hoi";
$l_NextPage = 2;
}else if($l_NextPage == 2){
echo "doei";
}
}
only the code dont work i tried empty, isset, $var == FALSE but everytime he makes $l_NextPage to 1. is there any solution i tried this too with session but even it don't work!
What am I doing wrong?
what happen when you refresh page, it assign $l_NextPage = 1 every time, thats why all the time hoi printed
you can use sessions for preserving value of variable after page refresh
try this code
// write this line of code at top of php block
session_start();
if (isset($_POST["register"]))
{
if (!isset($_SESSION["l_NextPage"]))
{
$_SESSION["l_NextPage"] = 1;
echo "helaas" . "</br>";
}
if($_SESSION["l_NextPage"] == 1)
{
echo "hoi";
$_SESSION["l_NextPage"] = 2;
}
else if($_SESSION["l_NextPage"] == 2)
{
echo "doei";
//unset( $_SESSION['l_NextPage'] ); unset varibale
}
}
after reaching at prefixed condition you can unset varible using
unset( $_SESSION['l_NextPage'] );
i have not tested code but this should work
you should try:
if(!isset($l_NextPage)) {
$l_NextPage = 1;
echo "helaas" . "</br>";
}
elseif($l_NextPage == 1) {
(...)
try like this,
if(!empty(trim($l_NextPage)))

What is the most succinct way to test if either of two variables are set?

What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;

Categories