php 字符串索引值,PHP:字符串索引不一致?

我创建了一个函数,该函数从硬编码的单词列表中随机生成一个短语.我有一个函数get_words(),该函数具有一串硬编码的单词,将其转换成一个数组,然后重新排列并返回.

get_words()由generate_random_phrase()调用,它会反复遍历get_words()n次,并且在每次迭代时,将n个单词连接到最终的短语中,该短语最终将返回给用户.

我的问题是,由于某种原因,PHP一直给我不一致的结果.它的确给了我一些随机的单词,但给出的单词数量却不一致.我将4个单词指定为默认单词,它给我的短语是1-4个单词,而不是4个单词.该程序非常简单,几乎难以置信,我无法查明确切的问题.似乎链中断开的链接是正在索引的$words数组,似乎由于某种原因有时索引编制失败.我不熟悉PHP,有人可以向我解释吗?

function generate_random_phrase() {

$words = get_words();

$number_of_words = get_word_count();

$phrase = "";

$symbols = "!@#$%^&*()";

echo print_r($phrase);

for ($i = 0;$i < $number_of_words;$i++) {

$phrase .= " ".$words[$i];

}

if (isset($_POST['include_numbers']))

$phrase = $phrase.rand(0, 9);

if (isset($_POST['include_symbols']))

$phrase = $phrase.$symbols[rand(0, 9)];

return $phrase;

}

function get_word_count() {

if ($_POST['word_count'] < 1 || $_POST['word_count'] > 9)

$word_count = 4; #default

else

$word_count = $_POST['word_count'];

return $word_count;

}

function get_words() {

$BASE_WORDS = "my sentence really hope you

like narwhales bacon at midnight but only

ferver where can paper laptops spoon door knobs

head phones watches barbeque not say";

$words = explode(' ', $BASE_WORDS);

shuffle($words);

return $words;

}

?>

解决方法:

在$BASE_WORDS中,选项卡和换行符在爆炸数组中占据了空间,这就是原因.删除换行符和选项卡,它将生成正确的答案.即:

$BASE_WORDS = "my sentence really hope you like narwhales bacon at midnight but only ferver where can paper laptops spoon door knobs head phones watches barbeque not say";

标签:arrays,php

来源: https://codeday.me/bug/20191029/1957295.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值