PHP using inner function variable in another function - php

I tried this code today! But it's not giving the output I expected.. this is my code..
<?php
namePrint('Rajitha');
function namePrint($name) {
echo $name;
}
wrap('tobaco');
function wrap($txt) {
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>
This code will print on screen
RajithaYour username is tobaco
but I want to get
RajithaRajithaYour username is tobaco
My question is: why is the $name variable in the wrap function not working?
Thanks.

Never use echo inside function to output the result. And never use global for variables.
You used echo inside function and because of that you get unexpected output.
echo namePrint('Rajitha');
function namePrint($name){
return $name;
}
echo wrap('tobaco');
function wrap($txt){
//global $name;
return "Your username is ".namePrint('Rajitha')." ".$txt."";
}
Output using echo in function Codepad
RajithaRajithaYour username is tobaco
Output1 using return in function Codepad
RajithaYour username is Rajitha tobaco

If you want to wrap a function around another you could simply pass a closure as one of the arguments:
function wrap($fn, $txt)
{
echo "Your username is ";
$fn();
echo ' ' . $txt;
}
wrap(function() {
namePrint('Rajitha');
}, 'tobaco');
This construct is very delicate; using function return values is more reliable:
function getFormattedName($name) {
return $name;
}
echo getFormattedName('Jack');
Then, the wrap function:
function wrap($fn, $txt)
{
return sprintf("Your username is %s %s", $fn(), $txt);
}
echo wrap(function() {
return getFormattedName('Jack');
}, 'tobaco');

Another option would be to pass $name as a parameter to the wrap function.
<?php
$name = 'Rajitha';
function namePrint($name){
echo $name;
}
function wrap($txt, $name){
echo "Your username is " . $name . " ". $txt;
}
namePrint($name);
wrap('tobaco', $name);
?>

$name should be declared and initialized as global variable.then you can the output you need.
The code should look like this.
<?php
$name = 'Rajitha';
namePrint($name);
function namePrint($name){
echo $name;
}
wrap('tobaco');
function wrap($txt){
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>

Related

echo statement for false php function

I have created a function as follows:
//function for first name field
function name ($fname) {
//validate to see if field is empty
if (empty($fname)) {
return (false);
}
$welcome_string = '<p> Welcome ' . $fname . '. We\'re glad you\'re here! Take a look around!</p>';
return $welcome_string;
}//end fname function
When the function passes the check I echo the function and get the welcome_string. However, I need to display an error outside of the function when it returns false. I cannot figure out how to do this. Below is the code where I call the function:
echo name($fname);
What you want to do is add a check for that:
$result = name($fname);
if ($result) {
echo $result;
} else {
echo "There was an error.";
}
Using a ternary if, you can do this in shorthand:
$result = name($fname);
echo $result ? $result : "There was an error.";
Or even shorter without introducing a new variable:
echo name($fname) ?: "There was an error.";
You could simply do:
$result = name($fname);
echo $result?$result:"error message";
<?php
function greeting($name)
{
if (empty($name))
return false;
$welcome_string = 'Welcome ' . $name . ". We're glad you're here! Take a look around!\n";
return $welcome_string;
}
foreach(['Rita', 'Sue', '', null, 0, '0'] as $name)
echo ($message = greeting($name))
? $message
: "Who are you?\n";
Output:
Welcome Rita. We're glad you're here! Take a look around!
Welcome Sue. We're glad you're here! Take a look around!
Who are you?
Who are you?
Who are you?
Who are you?

Variable arrays in class context

I am trying to accomplish a simple class method where the user submit its name to a form and it returns a greeting message for every name on the variable array, such as "Welcome John", "Welcome Mike", etc...
Doing this as a regular function is easy:
$arr = array('Mike', 'John', 'Molly', 'Louis');
function Hello($arr) {
if(is_array($arr)) {
foreach($arr as $name) {
echo "Hello $name" . "<br>";
}
} else {
echo "Hello $arr";
}
}
Hello($arr);
However, I can't make it work in class context:
$arr = array('Mike', 'John', 'Molly', 'Louis');
class greetUser {
public $current_user;
function __construct($current_user) {
$this->current_user = $current_user;
}
public function returnInfo() {
if(is_array($this->current_user)) {
foreach($this->current_user as $name) {
echo "Welcome, " . $name;
}
} else {
echo "Welcome, " . $this->current_user;
}
}
}
$b = new greetUser(''.$arr.'');
$b->returnInfo();
replace your $b = new greetUser(''.$arr.''); with $b = new greetUser($arr); and it will work :)
I was commiting a very silly mistake, as users pointed out, I was concatenating the variable when it was not necessary!

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

Variable inside the link

Would someone be able to help me with some php.
I am new to this and I am trying to solve the puzzle.
I am trying to combine the input data that user has provided with the link so that final output displays record for the user whose regid was provided by user via input text field.
Here is some code I came up with that obviously does not work.
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
echo '<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/';
return $this->view->string()->chunk($value->value);
echo '/1/NuNes.js"></script></div>';
}
}
To concatenate a string in PHP do this (note the periods, which are doing the work)
$str = "Line 1 " . $somevar . " Line 2";
return $str
Issuing a return terminates your function. I would build one string inside a variable then return that variable
The return ends the method, because it returns the value to the caller.
<?php
function fn() {
return "bar";
}
echo fn(); // will output bar
function fn2() {
echo "foo";
return "bar";
}
echo fn2(); // will output foobar
function fn3() {
return "foo" . fn();
}
echo fn3(); // will output foobar as well
?>
And here's how you can connect those three lines in the code snippet you posted:
<?php
class Fields_View_Helper_FieldStats extends Fields_View_Helper_FieldAbstract
{
public function fieldStats($subject, $field, $value)
{
$userid = preg_replace(trim($value->value));
// create user's profile address using their username/userid
$stats = $userid;
return
'<div style="margin:0px auto;"><script type="text/javascript" src="http://e1.statsheet.com/embed/' .
$this->view->string()->chunk($value->value) .
'/1/NuNes.js"></script></div>'
;
}
}
?>
And here's how you can concatenate strings:
<?php
$string1 = 'foo ' . fn() . ' bar';
$string2 = "foo 2" . fn() . " bar";
?>
And here's how you can embed stuff in variables (faster):
<?php
$string1 = fn();
$string1 = "foo {$string1} bar";
// Or with an object
class Foo {
public function fn(){}
}
$foo = new Foo();
$string1 = "foo {$foo->fn()} bar";
?>

How to do an if statement on a function in PHP?

I just realized that you can't just use an if statement on a function, for example this doesn't work:
function sayHello()
{
echo "Hello World";
}
if(sayHello())
echo "Function Worked";
else
echo "Function Failed";
I also saw that a function can't be put as the value of a variable. So how can I do an if statement to check if a function has executed properly and display it to the browser?
It's not working since sayHello() doesn't return anything place return true in there or something.
if (sayHello() === FALSE)
echo "Function Failed";
else
echo "Function Worked";
this will work
<?php
$name1 = "bobi";
function hello($name) {
if($name == "bobi"){
echo "Hello Bob";
} else {
echo "Morning";
}
}
hello($name1);
?>
function selam($isim)
{
if ($isim == 'ugur') {
return 'Selam '.$isim.' :)';
}
return 'Sen kimsin kardes?';
}
echo selam('ugur');

Categories