简体   繁体   中英

Assign variable to values in array php

This is what I want to do:

  1. Split a word into separate charachters. The input word comes from a form and can differ from each user.

  2. Assign variables to each charachter so that i can manipulate them separately.

Her's my code so far (which doesn't work). Apoligize if ther's a lot of stupid mistakes here, but I am new to 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++;
} 

?>

I'd like to end up with as many $tecken variables (With the names $tecken, t$tecken1, $tecken2 etc) as the number of charachters in the input.

All help much appreciated, as always!

I dont think its a good idea, but heres how you do it:

<?php
$input = 'Hello world!';
for($i = 0; $i < strlen($input); $i++) {
    ${'character' . $i} = $input[$i];
}

why do you want that? you can just go with:

$word = 'test';
echo $word[2]; // returns 's'
echo $word{2}; // returns 's'
$word{2} = 'b';
echo $word{2}; //returns 'b'
echo $word; // returns 'tebt'
...

You don't need to create separate variables for each letter because you have all the letters in an array. Then you just index into the array to get out each letter.

Here is how I would do it.

//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";

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