Question

im trying to play around in php, and its not going too well. I am trying to change a string through input fields in html

HTML PART

<form action="index2.php" method="POST">
<textarea name="text"><?php echo $search_replace; ?></textarea><br>
search<br><input type="text" name="search"><br>
replace<br><input type="text" name="replace">
<input type="submit">
</form>

php part

$text = $_POST[text];
$search = $_POST[search];
$replace = $_POST[replace];
$search_replace = str_replace($search, $replace, $text);

this works, but i wanted to try to put all the variables in a for loop just to try new things out. this is what i ended up with (probably should have used foreach):

$field = array('text', 'search', 'replace');
for($i = 0; i > 3; $i++) {
 if(isset($_POST[$field[$i]]) &&!empty($_POST[$field[$i]])) {
 $field[$i] = $_POST[$field[$i]];
 }
}
$search_replace = str_replace($field[1], $field[2], $field[0]);

$field[0] still has 'text' in it. shouldnt the value after the for loop be $_POST[$field[0]]? Do i need to create seperate arrays? one with the name of the fields and one empty to store $_POST[field[i]]?

Was it helpful?

Solution

Change like this:

for($i = 0; $i < 3; $i++) 
{
     if(isset($_POST[$field[$i]]) &&!empty($_POST[$field[$i]])) {
     $field[$i] = $_POST[$field[$i]];
}

In your code the loop was like this:

for($i = 0; i > 3; $i++)

In which you forgot to add $ symbol before the the second 'i' in your for loop.

And the second condition was $i > 3. You initialized $i as 0 and is checking whether $i is greater than 3, and if it is greater than 3, you increment $i, which is never going to happen as $i is 0 initially.

So it must be $i<3

OTHER TIPS

You can do it like so:

<?php
$posted = array();
if (! empty($_POST)) {
    foreach ($_POST as $pk => $pv) {
        if (! empty($k)) {
            $posted[$pk] = $pv;
        }
    }
}
?>

Because, $_POST is itself an array. And it has keys and values.

If a form element is posted, we get it by $_POST['varName'] means,

We are accessing the key varname of $_POST

Also, we are checking that its not empty. So only those variables will be extracted which are posted.

<?php
echo '<pre>';
print_r($posted);
echo '</pre>';
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top