removing last element from a multidimensional array in php - php

I have a textbox that iterates 5 times and displays values from the textbox into an array.
<form method="post" action="test.php">
<?php for($i = 0; $i < 5; $i++) {
echo "<input type='text' name='text1[]'/>";
} ?>
<input type="submit" name="confirm" value="confirm" />
</form>
<?php
$text1 = $_POST['text1'];
$count= count($text1);
if(isset($_POST['confirm'])) {
for($p = 0; $p < $count; $p++) {
echo print_r($p[$i]);
}
}
?>
I want to remove the last value (which is that repeating number 1) from the data and only display the names. The output of above is as follows:-
John1
Jack1
Peter1
Jane1
Jill1

echo print_r($p[$i]);
print_r prints content of $p[$i] and returns 1 that is passed to echo (and printed next to desired output). You don't need print_r here.

print_r sends $p[$i] to the output buffer and then it returns a boolean result, which will be true (or 1 when echoed out).
So, the solution is simply to not use print_r.
Always read the documentation when you are unsure about something. Pretty much anything you want to know about PHP can be found there.

Related

How to reset/change a variables value if while loop condition false in php

I have situation where i want to set some value to a php variable in a while loop. Please have a look at my code for better understanding.
$radioChecked = '';
$j=1;
while($j <= $someNumber){
$radioChecked = 'checked';
$j++;
}
Now i want after finishing while loop my $radioChecked variable should have an empty string.
Actually i am trying to do this:
i have some Radio buttons and i want to check some of them. how many checkboxes will be checked it will be depending on $someNumber variable.
Then i have checkboxes down:
for ($i = 0; $i < $total_radios; $i++){
<input type="radio" <?php echo $radioChecked; ?> />
}
Now here is the problem:
if i have 4 $total_radios then i am getting 4 radios displayed on the page which is good as i expecting that. If $someNumber is 2 then i want first 2 radio buttons to be checked. If $someNumber is 3 then i want first 3 radio buttons to be checked and so on.
But in my case it is checking all the Radio Buttons. I need some logic to reset $radioChecked variable to empty string if condition while loop condition false.
How can i do this?
Thanks.
Why not just do it in the loop?
foreach ($total_radios as $i => $total){
<input type="radio" <?php if ($i < $someNumber) echo 'checked'; ?> />
}
Mish-mash between php and html but the provided example is the same.
Perform the test against $someNumber around the echo statement.
for ($i = 0; $i < $total_radios; $i++){ ?>
<input type="radio" <?php if ($i < $someNumber) echo $radioChecked; ?> />
<?php
}
You were also missing the ?> and <?php around the HTML body of the for loop.
I think this would also work as a solution:
for ($i = 0; $i < $total_radios; $i++){
<input type="radio" <?php echo $radioChecked; ?> />
$j--;
if ($j == 0) {
$radioChecked = '';
}
}

PHP FOR loop taking values from form (post)

I have form with elements (text fields), 5 diference elements names:
name1a name1b
name2a name2b
name3a name3b
name4a name4b
name5a name5b
and php file:
for ($i = 1; $i <= 5; $i++) {
echo $i,"<br/>";
$name. $i .'a' = $_POST['name'.$i.'a'];
echo $name. $i .a;
}
It is posible read text fields with for loop or no? And pass values to sql query aswell?
you can use
extract($_POST);
like
echo $name1a;
echo $name1b;
you can access the value with the text-box names itself
It´s possible, but it´s a bad practice and I can´t recommend it you.
So, use arrays to store similar values from form (when you indexed your names, every times use arrays instead).
<input name="name[1]" ...> <!-- key isn't neccesary here, name[] will count from 0 -->
<input name="name[2]" ...>
<input name="name[3]" ...>
<?php
for ($i = 1; $i <= count($_POST['name']), $i++) {
echo $_POST['name'][$i] . '<br>'; // work directly with this variables/array, don't create duplicate vars
}
?>

Having Trouble with PHP Word Guessing Game

<?php
if(isset($_POST['submit'])) {
$guess = $_POST['guess'];
$count = isset($_POST['count']) ? $_POST['count']:0;
$count++;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guess the Word Game</title>
</head>
<body>
<div id = "header">
</div>
<div id = "word">
<?php
//create array
$words = array("aardvarks", "determine", "different", "greatness", "miserable");
$random = array_rand($words);
//choose a random word from array
$newWord = $words[$random];
$change = str_split($newWord);
//prints out array
/*foreach($change as $list) {
echo $list;
}*/
$masked = str_replace($change, '*', $change);
//prints masked array
foreach($masked as $hide) {
echo $hide;
}
?>
</div>
<div id = "guess">
<form name="guessLetter" method="POST" action=""
<p>Please input your guess below</p>
<input type="text" name="guess" id="guess"/><br />
<input type="hidden" name="count" id="count" value="<?php echo $count; ?>" />
<?php
?>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit'])) {
echo "Guess: ".$guess."<br />";
echo "Count: ".$count;
}
?>
</div>
</body>
</html>
Hi everyone
I am relatively new to PHP and in the process of creating a word guessing game.
I have created an array of words and then randomized them. Once a word has been chosen, I have split the word into an array. I have then created another array for the masked version of the word which appears on the screen.
I have been ok up to here, but I now need to use a loop to iterate through array to see if the letter guessed is actually in the word. I also want to tell the user how many times the letter appears and also update the masked version of the word, with the actual letter.
I have included my code so far and would really appreciate some help as I am stuck!!
I now need to use a loop to iterate through array to see if the letter guessed is actually in the word
$letter_is_in_word = stristr($selected_word, $guess);
// returns either false if not found, or a section of the string
// where it was found ($letter_is_in_word == true)
I also want to tell the user how many times the letter appears
$number_of_occurences = substr_count($selected_word, $guess);
... and also update the masked version of the word, with the actual letter.
// get your random word
$random = array_rand($words);
$selected_word = $words[$random];
// set up temporary array to store output letters or *
$output = array();
// split word into each letter
$letters = str_split($selected_word);
foreach($letters as $letter) {
// if the letter was guessed correctly, add it to the output array,
// otherwise add a *
$output[] = ($letter == $guess) ? $letter : '*';
}
// output the results (implode joins array values together)
echo implode($output);
Something to note here is that while you are tracking the guess count via hidden input field, you aren't tracking previous guesses. I would suggest you use a hidden input field to store previous guesses also.
At the top of your page:
$count = 0;
$guesses = array();
if(isset($_POST['guesses']))
$guesses = explode('|', $_POST['guesses']);
if(isset($_POST['submit'])) {
$guess = trim(strtolower($_POST['guess']));
if(!in_array($guess, $guesses))
$guesses[] = $guess;
$count = isset($_POST['count']) ? (int) $_POST['count'] : 0;
$count++;
}
Then further down:
<input type="hidden" name="guesses" id="guesses" value="<?=implode('|', $guesses)?>">
This allows you to track previous guesses (hidden field in this example is delimited by | characters). You'll then need to check that array when you decide which letters to * out:
foreach($letters as $letter) {
// if the current letter has already been guessed, add it to
// the output array, otherwise add a *
$output[] = in_array($letter, $guesses) ? $letter : '*';
}

Concat vars on a valuefields in a for cycle without showing the result

I have this page:
<?php
for($i=1; $i<=3; $i++){
$until_he.$i = htmlentities($_POST['until'.$i])
}
?>
<form action="" method...>
<?php
for($i=1; $i<=3; $i++){
...
print '<input name="until'.$i.'" id="until'.$i.'" class="textinput" value="'.$until_he.$i.'" type="date" min="'.date("Y-m-d").'"/>';
...
}
?>
...
Now:
$until_he
has content only once the form is posted, otherwise it's empty. On the other hand
$i
is already defined.
So as I load the page I get values 1, 2, 3 on the fields.
I'd like to get values on the files only once the user post the forum.
As I load the page the fields should be empty.
Thank you
Try this:
<?php
for($i=1; $i<=3; $i++){
$until_he.$i = htmlentities($_POST['until'.$i]);
$fieldValue = (trim($until_he.$i)==$i)?"":$until_he;
...
print '<input name="until'.$i.'"
id="until'.$i.'"
class="textinput"
value="'.$fieldValue.'"
type="date" min="'.date("Y-m-d").'"/>';
...
}
?>
Depends on what you want to accomplish and other code you have. In your example, you should use isset($until_he) which doesn't generate a warning if the variable is not set. Also, it works in the case the variable $until_he is set but empty. However, it will fail if you initialize $until_he to an empty value beforehand.

Any ideas why this wont print out

Revising for php and cant seem to get this to print the values out that i want
Any ideas?
Thanks
<form action="revision.php" method="GET">
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type="Submit" name="Calcuate"/>
</form>
<?php
if(isset($_GET['number'])){
$amount = count($number);
for($i=0; $i < $amount; $i++){
echo $number[$i];
}
}
?>
I think the actual problem with your code is that the quotation marks " are wrong you are using “ and ” instead of ". Replace those and everything will work.
EDIT: My answer is completely wrong. See #rmarimon in comments below.
Text fields can't be mapped to an array. You'll have to name them something ugly like "number1", "number2", etc and add them up with $_GET['number1'] + ...
<form action="revision.php" method="GET" enctype="multipart/form-data">
Change form to this.
The multipart tag must be used for this
you also need this for file uploads
and for printing use this
foreach ($_GET['number'] AS $key => $value)
{
echo "$key => $value";
}
because the array can be number[1] -> number[3]
It is not in your code but do you have
$number = $_GET["number"]
What you are doing is the correct way. This is similar to this other question.
The way I see it, there's a couple things you should change in your code, first, the names of the fields, you're trying to name them number[0], number[1], number[2] from the looks of it but it won't work that way, try naming them differenty or try to make a FOR cicle to create the fields with those custom names. Second, in order to save the array coming in the $_GET variable into the $number variable you need something like this:
if(isset($_GET['number']))
{
$number = $_GET['number'];
$amount = count($number);
for( $i = 0 ; $i < $amount ; $i++ )
echo $number[$i];
}
Hope this helps, if you're still having problems try posting or describing the context and what you have in mind for the form and the array.

Categories