猿问

如何在html中调用php的explode函数

<?php 

 function rand_word(){

 $lines = file("words.txt") ;

  $random_index = rand(0,count($lines)-1);

  $random_line = $lines[$random_index];

  $definition = explode("\t", $random_line)

 }

?>

<html>

  words: 

  part:

  definition:

</html>

两个问题:我如何在 html 中调用爆炸行,我尝试了下面的代码,但它们都不起作用。

<?=$definition[0]?>

<?php rand_word(); ?>

<?php echo rand_word(); ?>

<?php echo defintion[0]; ?>


文件中的一行例如: rescind verb to take away 或 remove


叮当猫咪
浏览 234回答 2
2回答

万千封印

您无法访问函数外部的局部变量,但您可以从函数返回以获取更多信息,请访问https://www.php.net/manual/en/language.variables.scope.php&nbsp; &nbsp; <?php&nbsp;&nbsp; &nbsp; &nbsp;function rand_word(){&nbsp; &nbsp; &nbsp; &nbsp; $lines = file("words.txt") ;&nbsp; &nbsp; &nbsp; &nbsp; $random_index = rand(0,count($lines)-1);&nbsp; &nbsp; &nbsp; &nbsp; $random_line = $lines[$random_index];&nbsp; &nbsp; &nbsp; &nbsp; return explode("\t", $random_line);&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; ?>&nbsp; &nbsp;...&nbsp; &nbsp; <?php echo reset(rand_word()); ?>

一只名叫tom的猫

您没有从函数返回任何值,您可以直接从函数示例中直接打印值:<?php&nbsp;&nbsp;function rand_word(){&nbsp;$lines = file("words.txt") ;&nbsp; $random_index = rand(0,count($lines)-1);&nbsp; $random_line = $lines[$random_index];&nbsp; $definition = explode("\t", $random_line);&nbsp; echo defintion[0];&nbsp;}&nbsp;rand_word();?>或者您可以从函数返回值以在外部使用...
随时随地看视频慕课网APP
我要回答