PHP 5 - Variables

+1 vote
566 views
added Dec 18, 2017 in PHP by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal

Sharing, Passing PHP variables to Javascript

<?php
$state     = $item['state'];
$area      = $item['area'];
$developer = $item['developer_name'];
?>
<script>
  var state = "<?php echo $state;?>"; 
  var area = "<?php echo $area;?>"; 
  var developer = "<?php echo $developer;?>"; 
</script>

5 Responses

0 votes
responded Mar 30, 2018 by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal
<!--Get PHP variable for JS variable-->

<script type="text/javascript">
var js_variable  = '<?php echo $php_variable;?>';
</script>

 

0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal
// JS/PHP Combined multiple variables as a link

var lookfordistrict = $('ol.breadcrumb li:nth-child(3) a'); 
var districtlink = "/map-search-property?listing_type=<?php print $field_prop_listing_type; ?>&state=<?php print $field_state; ?>&district=<?php print $field_district; ?>";
$(lookfordistrict).attr('href', districtlink);

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal
// Output the text and multiple variables

<?php
$sitename = "lazacode.org";
$google = "google.com";
echo "I'm a fan of " . $sitename . "and" . $google  . "!";
//output I'm a fan of lazacode.org and google !
?>


// Output the sum of two variables

<?php
$x = 5;
$y = 4;
echo $x + $y;
//output 9
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal

PHP Variables Scope

GLOBAL SCOPE = Variable declared outside function and only can be accessed outside the function.

<?php
$x = "global scope!!"; // global scope

function test1() {
    echo "<p>Variable $x will generate error</p>";
    // Call $x from this function will generate error, because this variable is declared outside this function
}
myTest();

echo "<p>$x will be shown here for sure because this echo is made outside the function</p>";
?>

 

LOCAL SCOPE = Variable declared inside function and only can be accessed inside the function.

<?php
function test2() {
    $x = "local scope!!"; // local scope
    echo "<p>$x will be shown here for sure because this echo is made within the function</p>";
} 
myTest();

echo "<p>Variable $x will generate error</p>";
// Call $x here will generate error, because the variable is declared inside test2 function
?>
0 votes
responded May 14, 2018 by LC Marshal Captain (25,790 points)
edited Jul 23, 2018 by LC Marshal
To get current_path in drupal

$path = current_path();
<a href="?showlogin=true&destination=<?php echo $path; ?>" class="btn btn-xs btn-success">

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...