I have two functions that print some values. I need to use the variable $mv in the second function. However, $mv can only be defined in the first function. I have tried all types of PHP global examples and none of them has allowed the $mv variable to be used or visible or accessible in the second function.
function printMobilePrev(&$mobileprevresults) {
if (count($mobileprevresults->getRows()) > 0) {
$mv = $mobileprevRows[0][0];
$mobileprevRows = $mobileprevresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
} else {
print '<p>No results found.</p>';
}
}
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
$mobdiff = ($mobcur - $mv);
$mobpctchg = ($mobdiff / $mobprev) * 100;
$mobilecurrRows = $mobilecurrresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
echo '<p>Previous period (sessions): '.$mv.'..............................';
echo '<p>Current period (sessions): '.$mobilecurrRows[0][0].'..............................';
if ($mobdiff > 0){
echo '<p>Percent increase: '.$mobpctchg.'..............................';
} else {
echo '<p>Percent decrease: '.$mobpctchg.'..............................';
}
} else {
print '<p>No results found.</p>';
}
}
You can use the global scope:
That is what you want to do:
$mv = 0;
function function1()
{
global $mv;
$mv = 'whatever';
//code
}
function function2()
{
global $mv;
// use $mv;
}
You have to predefine that variable OUTSIDE any function, and then you can use Global to get that to any function.
You can pass it by reference. For example
function doSomething(&$mv) {
$mv = 1;
}
function doSomethingElse($mv) {
return $mv;
}
$mv = 0;
doSomething($mv);
echo doSomethingElse($mv); //Output: 1
You could return $mv after your print and save that in a var to pass to the next function:
$printMobilePrev = printMobilePrev();
function printMobilePrev(&$mobileprevresults) {
$mv = $mobileprevRows[0][0];
...
print '<p>No results found.</p>';
return $mv;
...
}
$printMobileCurr = printMobileCurr(&$mobilecurrresults,$mv);
function printMobileCurr(&$mobilecurrresults,$mv) {
......
}
Most likely you have to make a correct use of globals.
declare your $mv variable as global before asigning it a value on your first function
global $mv;
$mv = $mobileprevRows[0][0];
use global at the begining on your second function before using it
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
global $mv;
Related
I'm trying to add 1 to a number each time a function is called, but for some reason, the total number is always same.
Here is my current code:
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
echo $total;
}
draw_card();
draw_card();
?>
Personally, I would not use globals, but if I was forced at gunpoint I would handle state within the function, so outside variables did not pollute the value. I would also make an arbitrary long key name which I would not use anywhere else.
<?php
function draw_card($initial = 0) {
$GLOBALS['draw_card_total'] = (
isset($GLOBALS['draw_card_total']) ? $GLOBALS['draw_card_total']+1 : $initial
);
return $GLOBALS['draw_card_total'];
}
// optionally set your start value
echo draw_card(1); // 1
echo draw_card(); // 2
https://3v4l.org/pinSi
But I would more likely go with a class, which holds state by default, plus its more verbose as to whats happening.
<?php
class cards {
public $total = 0;
public function __construct($initial = 0)
{
$this->total = $initial;
}
public function draw()
{
return ++$this->total;
}
public function getTotal()
{
return $this->total;
}
}
$cards = new cards();
echo $cards->draw(); // 1
echo $cards->draw(); // 2
echo $cards->getTotal(); // 2
https://3v4l.org/lfbcL
Since it is global already, you can use it outside the function.
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
//echo $total;
}
draw_card();
draw_card();
draw_card();
echo "Current Count :", $total;
?>
Result :
Current Count :3
This will increment the number of times you call the function.
Since you echoed the result/total each time without a delimiter, you might have considered the output to be 12(Assumption)
Functions have a scope.. you just need to bring $total into the scope of the function... best to not do it globally but as an argument.
$total = 0;
function draw_card($total) {
return $total + 1;
}
$total = draw_card($total);
//Expected Output = 1
$total = draw_card($total);
//Expected Output = 2
Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}
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/>";
Here is my script.
I declared few variable outside function. I want to use it in function, would it be available?
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('follow.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$userid = $content->{'id'};
$temp = "1";
$tweets1 = $connection->get("https://api.twitter.com/1.1/statuses/retweets_of_me.json?count=200");
$tweets3 = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?trim_user=true&include_rts=true");
$tweets4 = $connection->get("https://api.twitter.com/1.1/statuses/home_timeline.json?include_rts=true&trim_use=true");
foreach ($tweets1 as $item)
{
$text = $item->text;
$follow_count = getfollow($m[1]);
echo "followe count is $follow_count <br>";
lookup($item->user->id_str);
}
function lookup($userid)
{
//echo "userid : $userid temp : $temp";
$tweets5 = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id='.$userid.' ");
$CONNECTION IS not availabl here? WHY?
foreach ($tweets5 as $item)
{
$text = $item->name;
}
return;
}
?>
A function has its own scope. You have to provide all variables you want to use in arguments except if they are in the $_SESSION, $_SERVER etc. variables.
Hand it over via parameter:
function lookup($userid, $connection) {
//code here
}
Only Superglobals are availible inside functions. Everything else is handed over via parameters.
You can use outside variable by defining them as global or you can pass them to functions as a parameters.
$str= 'str';
function test()
{
global $str;
echo $str;
}
or
function test($str)
{
echo $str;
}
using the global keyword should do the trick:
$foo = '123';
function bar() {
global $foo;
echo $foo;
}
but the way I see it, you could just pass the variable to that function instead.
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.