Putting if statements inside php function with parameters? - php

Im trying to put these if statements inside a php function to get results. So far its not working. I know this may be an easy solution, but I am new to PHP and the other examples that I looked at didnt help me a lot.
FUNCTION
$startdate='';
$enddate='12/3/2020';
function startEnd($startdate,$enddate){
if($startdate==''){
$startdate='Anytime';
}
if($enddate==''){
$enddate='Anytime';
}
}
CALL
startEnd($startdate,$enddate);
echo $startdate;
echo $enddate;

You cannot use variables that are outside of the scope of the function.
Once it is passed as an argument, in the function, it will be treated as a completely new variable. Unless you reintroduce them to the scope with global.
You can, however, pass a reference of a variable to a function using the & operator in the parameters.
function startEnd(&$string1, &$string2) {
if ($string1 === '') {
$string1 = 'Anytime';
}
if ($string2 === '') {
$string2 = 'Anytime';
}
}
startEnd($startdate, $enddate);

Related

PHP Functions returning an array

I am having some issues with my function which returns an array, I decided to try and use an OO approach to my php code and try to make a class with a few static functions since I decided I don't want to access it using an object. In my code, within the same class, I decided to make the following function:
public static function decideCategory($tweets) {
$tweet = $tweets;
if(in_array($tweet, self::$food)) {
echo "\nOur " . $tweet . " is under food\n";
} //if statements of the same nature below as well.
}
Now, this function works in the sense that it does not throw an error where $food is definded as an array at the top. However, originally I simply had $food defined at the top as just a private static variable, and then I had the following function which I passed into the in_array.
public static function getFood()
{
self::$food = array("Wendys", "McDonalds", "Wendy's", "Chic Fil A", "Chic-Fil-a", "Burger", "TGI", "BBQ", "Grilling", "Wine", "Tasty", "Yum", "IHOP", "Pancakes", "Pizza", "Cake"
,"Baking");
return self::$food;
}
However, it would return an error saying that in_array expects an array value for its second argument, but that instead it sees that a null was passed instead. Why is that and how can I use methods to do my comparison rather than the variables themselvs. If this were Java this would be how I would do it, and as such I cannot see why php would have these issues as it appears to follow a similar logic with returns.
Yes it would error because until you call self::getFood() Self::$food is null if you have declared it as
static $food;
update your method as below
public static function decideCategory($tweets)
{
$tweet = $tweets;
$food = self::getFood();
if(in_array($tweet, $food)) {
echo "\nOur " . $tweet . " is under food\n";
} //if statements of the same nature below as well.
}

Using external variable in PHP [duplicate]

I have this code:
if(!isset($_GET["act"]))
{
$display->display("templates/install_main.html");
if(isset($_POST["proceed"]))
{
$prefix = $_POST["prefix"];
}
}
if($_GET["act"] == "act")
{
echo $prefix;
}
Basically I've made a similar question before, thing is, HOW can I make the variable accessible? please mention if there is any way to do so, even with changing the way it's done (someone told me it's possible with a class but not quite sure how it can be done), or any other way to make it accessible.
Thanks!
PHP's variable scope is function-level. $prefix would be available in your second if() IF the other if()'s evaluated to true and actually executed that $prefix = ... code.
e.g.
if (true) {
$foo = 'bar'; // always executes
}
if (false) {
$baz = 'qux'; // never executes
}
echo $foo; // works just fine
echo $baz; // undefined variable, because $baz='qux' never executed.
Also note that PHP is not capable of time travel:
echo $x; // undefined variable;
$x = 'y';
echo $y; // spits out 'y'
"earlier" code will not have "later" variables available, because the code that actually creates/assigns values to those variables won't have executed yet.

php variable not detected

im having trouble with my php program, it seems that my array variable being declared earlier wasn't detected in a function. Here's my code :
$msg = array(
//Errors List
'Error1' => 'Error 1',
'Error2' => 'Error 2'
);
//Class for outputting Messages
class Message {
static function Info($string) { echo $string; }
static function Error($string) { echo $string; }
}
//Functions
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
when i run it, and example i test the program like this..
$test = 'blabla';
function1($test);
it says the msg variable was undefined. Can anyone tell me how to resolve this?
Thanks in advance.
There are three ways to solve this issue.
Passing the required global var as a parameter
In my opinion, this is the preferred solution, as it avoids the pollution of your function with global variables. Global variables tend to introduce unexpected side effects and make maintenance and reuse of code a lot harder. A very extensive article on why you should avoid globals whenever possible (and some alternative solutions) can be found in the c2 wiki
function function1($var1,$mesg) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($mesg['Error1']);
}
}
The call to function1 changes to
function1($test,$msg);
Using global:
Same effect as the one just below, other notation.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}
Using the $GLOBALS superglobal
Some sources say this form is slightly faster than the one using global
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($GLOBALS['msg']['Error1']);
}
}
you can not use $msg as a local variable in function.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}

PHP function (shortcut) use

I have set in myFile.php this function:
function monthLanguage()
{
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}
I was thinking to wrap this if statement into a function to call it where is needed as a kind of short code.
I call it like this:
monthLanguage();
but I get error message: Call to undefined function
Any help on how to reach my short code intent?
Are you including the monthLanguage function the file you are using it in? Also, I spotted two issues with this code. You are not initiating the array called $dayName and nothing is being returned so the function will not send back output. It should be like this.
function monthLanguage()
{
$dayName = array();
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
Also, the $this is not clear since that is usually used in the scope of a class, so perhaps you need to set the function like this:
function monthLanguage($lang)
{
$dayName = array();
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
And you would then call the function in PHP like this:
monthLanguage($this->lang);
Or like this:
monthLanguage($lang);
But it is unclear where this function is being placed or used, so clarify that to decide which is the best way to handle.
I don't think you can use $this->lang - it's usually reserved for a method if I'm not mistaken.
Try replacing the function with this, should work like a charm.
function monthLanguage($lang) {
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}

Getting 'Fatal error: Call to undefined function' when using a function inside an if statement?

Ok, so I just finished off a function for validating the firstname field on a form.
This function works correctly on its own.
But since I want to make this function re-usable for more than one website, I added an if statement for whether or not to use it. The following code explain this:
Related PHP code:
//Specify what form elements need validating:
$validateFirstname = true;
//array to store error messages
$mistakes = array();
if ($validateFirstname=true) {
//Call first name validation function
$firstname = '';
if (!empty($_POST['firstname'])) {
$firstname = mysql_real_escape_string(stripslashes(trim($_POST['firstname'])));
}
$firstname = validFirstname($firstname);
if ($firstname === '') {
$mistakes[] = 'Your first name is either empty or Enter only ALPHABET characters.';
}
function validFirstname($firstname) {
if (!ctype_alpha(str_replace(' ', '', $firstname))) {
return '';
} else {
return $firstname;
}
}
}
So without this if ($validateFirstname=true) the code runs fine, but the moment I add it; I get the following error message:
Fatal error: Call to undefined function validFirstname()
Are you not able to use functions in if statements at all in PHP? I'm fairly new to using them in this way.
Conditional functions (functions defined inside the conditions) must be defined before they are referred. Here's what manual says:
Functions need not be defined before they are referenced, except when
a function is conditionally defined as shown in the two examples
below.
When a function is defined in a conditional manner such as the two
examples shown. Its definition must be processed prior to being
called.
So if you want to use it that way, you should put it either at the beginning of the if condition or outside the condition.
// Either:
if ($validateFirstname==true) {
function validFirstname($firstname) {}
}
// Or, and I'd rather do it this way, because function is
// created during "compilation" phase
function validFirstname($firstname) {}
if ($validateFirstname==true) {
// ...
}
Also not that function (even if created inside the condition) is pushed to global scope:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
So once code is evaluated it doesn't matter if it's declared inside condition or intentionally in global scope.
Functions that are declared in a conditional context (like if body), you can only use after their declaration.
if ($validateFirstname == true) {
//Call first name validation function
function validFirstname($firstname) {
// function body
}
// $firstname initialisation
$firstname = validFirstname($firstname);
// ...
}
(P.s.: changed $validateFirstname = true to $validateFirstname == true which should be what you want)
if($validateFirstname=true)
you are assigning the value "true" to $validateFirstname here
you should use a "==" for comparison e.g
if($validateFirstname==true)
that might help your "if" problem

Categories