If statement inside setted function - php

How to edit already setted function inside () if I want inside that function if statement
<?php
$a = 1;
function writeMsg($x) {
echo $x;
}
writeMsg(
Hello,
if ($a == 1) {
echo "men";
} else {
echo "women";
}
);
?>

I think you want to prepare the message first then write message.
<?php
$a = 1;
function writeMsg($x) {
echo $x;
}
$message = 'Hello, '. ( $a == 1 ? 'men' : 'women');
writeMsg($message);

Related

PHP – use outside function with if-statements inside foreach-loop [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
I'm new to PHP, please be gentle.
What do I need to change to make this work in PHP?
<div>some HTML here</div>
<?php
function typ__1() {
if ($temperature >= 29) {
$hot = true;
} else {
$hot = false;
}
}
?>
<?php foreach (array_slice($data->something->something, 0, 5) as $day):
$temperature = $day->temperature;
typ__1();
if ($hot == true) {
$bottom = "Shorts";
} else if ($hot == false) {
$bottom = "Pants";
}
<div><?php echo $bottom ?></div>
<?php endforeach ?>
So the main issue/question is if I'm using the function correctly. Can I write if-statements in an outside function and then use them inside a
foreach-loop? The reason/goal is to shorten the foreach-loop.
(This is a reduced example, so there could be a typo somewhere in there.)
Thanks for your help!
Everything is about scope of PHP variables. You should "inject" variable into function like this:
<div>some HTML here</div>
<?php
function typ__1($temperature) {
if ($temperature >= 29) {
return true;
}
return false;
}
?>
<?php foreach (array_slice($data->something->something, 0, 5) as $day):
if (typ__1($day->temperature)) {
$bottom = "Shorts";
} else if (typ__1($day->temperature)) {
$bottom = "Pants";
}
<div><?php echo $bottom ?></div>
<?php endforeach ?>
http://php.net/manual/en/language.variables.scope.php
Add parameter in your function and return a value.
<?php
function typ__1($temperature) {
if ($temperature >= 29) {
$hot = true;
} else {
$hot = false;
}
return $hot;
}
?>
<?php foreach (array_slice($data->something->something, 0, 5) as $day):
$temperature = $day->temperature;
$hot=typ__1($temperature);
if ($hot == true) {
$bottom = "Shorts";
} else if ($hot == false) {
$bottom = "Pants";
}
<div><?php echo $bottom ?></div>
<?php endforeach ?>

Put IF condition inside a variable

Is there any way to put conditions within a variable and then use that variable in an if statement? See the example below:
$value1 = 10;
$value2 = 10;
$value_condition = '($value1 == $value2)';
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
I understand this may be a bizarre question. I am learning the basics of PHP.
No need to use strings. Use it directly this way:
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
Or to evaluate, you can use this way using ", as it expands and evaluates variables inside { ... }.
I reckon it might work! Also, using eval() is evil! So make sure you use it in right place, where you are sure that there cannot be any other input to the eval() function!
Depending on what you are trying to do, an anonymous function could help here.
$value1 = 10;
$value2 = 10;
$equals = function($a, $b) {
return $a == $b;
};
if ($equals($value1, $value2)) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
However, I would only do it like this (and not with a regular function), when you make use of use ().
== operator evaluates as a boolean so you can do
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
Just assign result of comparision to variable.
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
An if statement tests a boolean value. You could have something like this:
if (true) {
You can assign boolean values to a variable:
$boolValue = true;
You can use variables in your if statement:
if ($boolValue) {
// true
In your example:
$value_condition = $value1 == $value2; // $value_condition is now true or false
if ($value_condition) {

PHP function varying parameters

I couldn't find about my issue on google and SO. Hope, i can explain you.
You'll understand when looked following function:
function get_page($identity)
{
if($identity is id)
$page = $this->get_page_from_model_by_id($identity);
elseif($identity is alias)
$page = $this->get_page_from_model_by_alias($identity);
}
My used function:
get_page(5); // with id
or
get_page('about-us'); // with alias
or
get_page(5, 'about-us'); // with both
I want to send parameter to function id or alias. It should be only one identifier.
I dont want like function get_page($id, $alias)
How can i get and know parameter type with only one variable. Is there any function or it possible?
if(is_numeric($identity)) {
$page = $this->get_page_from_model_by_id($identity);
}
elseif(is_string($identity)) {
$page = $this->get_page_from_model_by_alias($identity);
}
elseif(func_num_args() === 2) {
$id = func_get_arg(0);
$alias = func_get_arg(1);
//do stuff
}
Use is_string() to find whether input is integer or character.
You should make use of func_get_args()
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Source
Here's a complete solution:
function get_page()
{
$alias = false;
$id = false;
foreach(func_get_args() as $arg)
if(is_string($arg))
$alias = $arg;
else if(is_int($arg))
$id = $arg;
}
Assuming id is always a number, you could test for it with php's is_numeric()
function get_page($identity)
{
if(is_numeric($identity) {
$page = $this->get_page_from_model_by_id($identity);
} else {
$page = $this->get_page_from_model_by_alias($identity);
}
}

PHP global variables not working inside a function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php function variable scope
I am using below code to test with a global variable. It seems that a global variable cannot be compared inside a function.
Why is it not displaying 'hello world' in the output?
Below is the code that I am trying:
<?php
$bool = 1;
function boo() {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
?>
When I remove function boo(), 'hello world' is displayed. Why is it not displaying when function exists?
use global $var to access your variable
<?php
$bool = 1;
function boo() {
global $bool;
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
boo();
?>
Or a safer way using pointers would be to
function boo(&$bool) {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
Looks like homework, still:
<?php
$bool = 1;
boo();
function boo() {
global $bool;
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
?>
Or
<?php
$bool = 1;
boo(&$bool);
function boo(&$bool) {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
?>
Call you function, and pass $bool as a parameter and return the value.
$bool = 1;
$bool = boo($bool);
function boo($bool) {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
return $bool;
}
use this way
$bool = 1;
function boo($bool) {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
boo($bool);

Get the name of a variable passed into a PHP function?

I just threw this together to help in debugging some PHP scripts. As you can see, it is sloppy but I am going to improve it some more.
My debug function has 2 variables passed in, a variable name and a variable value.
Is it possible to just pass in the variable and somehow get the name of the variable without manually doing it like I have it set now?
The Function
<?php
function debug($varname, $var)
{
echo '<br>' . $varname;
// $var is a STRING
if (is_string($var)) {
echo ' (string) = ' . $var . '<br>';
// $var is an ARRAY
} elseif (is_array($var)) {
echo ' (array) = <pre>';
print_r($var);
echo '</pre><br>';
// $var is an INT
} elseif (is_int($var)) {
echo ' (int) = ' . $var . '<br>';
// $var is an OBJECT
} elseif (is_object($var)) {
echo ' (object) = <pre>';
var_dump($var);
echo '</pre><br>';
}
}
The Test
$testString = 'just a test!';
$testArray = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$testInt = 1234567890;
$testObject = new stdClass;
$testObject->someVar1 = 'testing123';
$testObject->someVar2 = '321gnitset';
debug('$testString', $testString);
debug('$testArray', $testArray);
debug('$testInt', $testInt);
debug('$testObject', $testObject);
?>
The Result...
$testString (string) = just a test!
$testArray (array) =
Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)
$testInt (int) = 1234567890
$testObject (object) =
object(stdClass)#1 (2) {
["someVar1"]=>
string(10) "testing123"
["someVar2"]=>
string(10) "321gnitset"
}
If you want to know the name, why not just pass a string constant of the name of the variable, and use global array to access it (for procedural programs)
function foo($var) {
echo $var; //name of the variable
echo $GLOBALS[$$var]; //value of the variale
}
$bar = 'a string';
foo('bar');
Check out this php function func_get_arg()
Actually... it looks like you can't really do it... check this other question How to get a variable name as a string in PHP?
debug_print_backtrace() is your friend! Add it to your debug() function.
If you still want only the calling function name you can use debug_backtrace() and search in the returned array for the name of the previous function, identified as "function" in the associative array result!
I put together these functions for my own debugging just copy and save it in a separate file, include it and use the function d() to call the fancy debug print. it suppose to color code the results based on the type of variable passed.
if(!defined('m_debug')) {define('m_debug', 1);}
function d($var) {
if (m_debug) {
$bt = debug_backtrace();
$src = file($bt[0]["file"]);
$line = $src[ $bt[0]['line'] - 1 ];
//striping the inspect() from the sting
$strip = explode('d(', $line);
$matches = preg_match('#\(#', $strip[0]);
$strip = explode(')', $strip[1]);
for ($i=0;$i<count($matches-1);$i++) {
array_pop($strip);
}
$label = implode(')', $strip);
d_format($var, $label);
}
}
function l() {
global $super_dump_log;
if (func_num_args() > 0) {
$array = func_get_args();
array_merge($super_dump_log, $array);
} else {
foreach($super_dump_log as $log){
//
}
}
}
function d_format($var, $label) {
$colorVar = 'Blue';
$type = get_type($var);
$colorType = get_type_color($type);
echo "<div class='m_inspect' style='background-color:#FFF; overflow:visible;'><pre><span style='color:$colorVar'>";
echo $label;
echo "</span> = <span class='subDump' style='color:$colorType'>";
if ($type == 'string') {
print_r(htmlspecialchars($var));
} else {
print_r($var);
}
echo "</span></pre></div>";
}
function get_type($var) {
if (is_bool($var)) {
$type = 'bool';
} elseif (is_string($var)) {
$type = 'string';
} elseif (is_array($var)) {
$type = 'array';
} elseif (is_object($var)) {
$type = 'object';
} elseif (is_numeric($var)) {
$type = 'numeric';
} else {
$type = 'unknown';
}
return $type;
}
function get_type_color($type) {
if ('bool' == $type) {
$colorType = 'Green';
} elseif ('string' == $type) {
$colorType = 'DimGrey';
} elseif ('array' == $type) {
$colorType = 'DarkOrchid';
} elseif ('object' == $type) {
$colorType = 'BlueViolet';
} elseif ('numeric' == $type) {
$colorType = 'Red';
} else {
$colorType = 'Tomato';
}
return $colorType;
}
You can do this from the other end. Pass the variable name in a string variable and then call it with $$ to pass the actual variable. I made my_var_dump function:
function my_var_dump($varName, $var, $line = false, $func = false)
{
if ($func) $func = ' in function ' . $func;
if ($line) $line = ' at line ' . $line;
echo '<pre>DEBUG $' . $varName . $line . $func . PHP_EOL;
var_dump($var);
echo '</pre>' . PHP_EOL;
}
Call this function like this:
my_var_dump($varName = "some_var_name", $$varName, __LINE__, __FUNCTION__);
SOLUTION :
$argv — Array of arguments passed to script
EXAMPLE :
<?php
var_dump($argv);
?>
REFERENCE :
PHP's $argv documentation

Categories