Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function to return string

I am fairly new to PHP. I have a function which checks the cost of price. I want to return the variable from this function to be used globally:

<?
function getDeliveryPrice($qew){
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    return $deliveryPrice;                          
}
// Assuming these two next lines are on external pages..
getDeliveryPrice(12);
echo $deliveryPrice; // It should return 20

?>
like image 575
TheBlackBenzKid Avatar asked Sep 06 '12 09:09

TheBlackBenzKid


2 Answers

<?php
function getDeliveryPrice($qew){
   global $deliveryPrice;
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    //return $deliveryPrice;                          
}
// Assuming these two next lines are on external pages..
getDeliveryPrice(12);
echo $deliveryPrice; // It should return 20

?>
like image 70
Mansoorkhan Cherupuzha Avatar answered Oct 15 '22 07:10

Mansoorkhan Cherupuzha


You should simply store the return value in a variable:

$deliveryPrice = getDeliveryPrice(12);
echo $deliveryPrice; // will print 20

The $deliveryPrice variable above is a different variable than the $deliveryPrice inside the function. The latter is not visible outside the function because of variable scope.

like image 21
Jon Avatar answered Oct 15 '22 06:10

Jon