简体   繁体   中英

how we can assign single value of array to any variable in javascript

<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
var gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>

You're not looking to assign a single value of the array; you're looking for the whole array. Your JavaScript loop is trying to iterate over the entire $abc array from PHP.

Something like this would work:

var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
    var gdf = abc[i];
    alert("value = " + gdf);
}

Firstly, to build a PHP array you should be using this notation:

<?php

$abc = array('abc', 'cde', 'fre');

?>

Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. You can do something like this instead, performing the loop in PHP:

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    <?php foreach ( $abc as $el ): ?>
    alert('value=<?php echo $el ?>');
    <?php endforeach ?>
</script>

Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it.

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    var abc = <?php echo json_encode($abc) ?>;

    for ( var i = 0; i < abc.length; i++ ) {
        alert('value=' + abc[i]);
    }
</script>

Following your comment, I think this is what you are trying to do:

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php

for ($i = 0; $i < count($abc); $i++) {
    echo "{$abc[$i]}";
    if ($i != (count($abc)-1)) echo ", ";
}

?>';
</script>

Will output:

http://codepad.org/KjEH5CmN

<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>

NOTE

Using implode if you want a single variable would also work well:

http://codepad.org/UwukCY4m

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM