Showing posts with label assign. Show all posts
Showing posts with label assign. Show all posts

Friday, April 10, 2015

Assign value or array in PHP variable to Javascript variable.

<?php
$name = 'Einstein';
$categories = array('1'=>'Red', '2'=>'Green', '3'=>'Blue');
?>

<script type="text/javascript">
// Assign a PHP value/string to JS variable.
var name = '<?php echo $name; ?>';
console.log(name);                       // Einstein

// Assign a PHP array to JS variable.
var categories = JSON.parse('<?php echo json_encode($categories); ?>');
console.log(categories[3]);           // Blue
</script>

Wednesday, July 16, 2014

Static variables in PHP

Declaring a variable with a value inside function as static, is will not re-declare or reassign the value when every time that function will called. That is, the last assigned value will remains on that variable.

<?php
function test()
{
    static $a = 1;
    echo $a;
    if ($a <= 10) {
        ++$a;
        test();
    }
}

test(); // Will print: 1234567891011
test(); // Will print: 11
?>

Note:
1. We can not use any expression on declaring of static variables. Ex: static $a=5+6;  // Is wrong.
2. Declaring a variable as static on outside of function not make sense. Because it will not going to re-call in future, except in some cases like using goto statements.

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS...