[英]Assign variable to values in array php
这就是我想做的:
将一个单词拆分为单独的字符。 输入的单词来自表单,并且可能与每个用户不同。
给每个字符分配变量,以便我可以分别操作它们。
到目前为止,她是我的密码(无效)。 如果在这里有很多愚蠢的错误,请进行举报,但是我是PHP新手。
<?php
$word = $_POST['input'];
//split word into charachters
$arr1 = str_split($word);
//assigning a variable to each charchter
$bokstaver = array();
while($row = $arr1)
{
$bokstaver[] = $row[];
}
$int_count = count($bokstaver);
$i=0;
foreach ($bokstaver as $tecken) {
$var = 'tecken' . ($i + 1);
$$var = $tecken;
$i++;
}
?>
我想最终得到与输入中字符数量一样多的$ tecken变量(名称为$ tecken,t $ tecken1,$ tecken2等)。
一如既往地感谢所有帮助!
我认为这不是一个好主意,但是请按以下步骤操作:
<?php
$input = 'Hello world!';
for($i = 0; $i < strlen($input); $i++) {
${'character' . $i} = $input[$i];
}
你为什么要那个? 您可以选择:
$word = 'test';
echo $word[2]; // returns 's'
echo $word{2}; // returns 's'
$word{2} = 'b';
echo $word{2}; //returns 'b'
echo $word; // returns 'tebt'
...
您不需要为每个字母创建单独的变量,因为您将所有字母都放在一个数组中。 然后,您只需索引数组即可获取每个字母。
这就是我要怎么做。
//get the word from the form
$word = $_POST['input'];
//split word into characters
$characters = str_split($word);
//suppose the word is "jim"
//this prints out
// j
// i
// m
foreach($characters as $char)
print $char . "\n"
//now suppose you want to change the first letter so the word now reads "tim"
//Access the first element in the array (ie, the first letter) using this syntax
$characters[0] = "t";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.