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]]?
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
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>';
?>
Related
I'm having some doubt doing some for each loop, so i have an immense variable names ranging from $a1 - $a120
What I'm trying to do is doing a for each loop from where I can get each of thoose by using an indexing system.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var = ${"a".$i}; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
It is not good for the loops. But you can use it, if you can not change your codes.
I just added
$var_name="a".$i;
$var = $$var_name;
And the full code is below.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var_name="a".$i;
$var = $$var_name; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
You should update the code to use an array.
$data = [];
$data["a116"] = "N69";
$data["a117"] = "V52";
$data["a118"] = "V53";
$data["a119"] = "V54";
$data["a120"] = "V55";
Now you can use a foreach loop getting the key/value pairs
foreach($data as $key => $value){
$sheet->setCellValue($key, $value);
}
So I have declared a Session array and initialized it with zeroes. It's basically a multidimensional array. However, I'm thinking of converting it to a regular array because everytime I test whether a value exists or not using the in_array() function, it fails. It keeps adding existing values.
<?php
session_start();
$_SESSION['numbers'] = array(
array(0,0,0,0,0), //row1
array(0,0,0,0,0), //row2
array(0,0,0,0,0), //row3
array(0,0,0,0,0), //row4
array(0,0,0,0,0) //row5
);
?>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$userInput = $_POST["num"];
for($r = 0; $r<sizeof($_SESSION['numbers']); $r++){
for($c = 0; $c<sizeof($_SESSION['numbers']); $c++){
$colVal = $_SESSION['numbers'][$r][$c];
insertInputAt($r,$c,$userInput);
}
}
}
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
?>
If I enter lets say 5, it inserts the input 5 to all rows and columns. I get 25 echos of value of 5 even if I put a !in_array() condition
I thought maybe if I parse the $_SESSION['numbers] as a regular array within the insertInputAt() method, the !in_array() condition might work accurately.
Thank you.
Modify your insertInputAt function to this:
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'][$row])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
First of all, you do not need to initialize $_SESSION['numbers'].
<?php
session_start();
$userInput = $_POST["num"] = 1;
for($r=0;$r<count($_SESSION['numbers']);$r++){
$found = 0;
for($c=0;$c<count($_SESSION['numbers'][$r]);$c++){
if(($_SESSION['numbers'][$r][$c]==0)&&(myfunction($_SESSION['numbers'],$userInput)==0)){
$_SESSION['numbers'][$r][$c] = $userInput;unset($_POST['num']); $found=1;break;
}
}
if($found==1)break;
}
function myfunction($array,$value){
foreach($array as $q){
if(!in_array($value,$q)){
for($i=0;$i<count($q);$i++){
if($q[$i]==0) return false;
}
}
}
}
echo "<pre>";print_r($_SESSION['numbers']);
?>
I'm using a php script to randomly show images. I've duplicated this script three times because I wanted to show three random images at once - I'm unsure of how to change the php code to show 3 images.
The problem is, I don't want to run into the chance of all three scripts showing the same images at once. Is there something that I could add to this code to make sure that each image displayed is always different?
<?php
$random = "random.txt";
$fp = file($random);
srand((double)microtime()*1000000);
$rl = $fp[array_rand($fp)];
echo $rl;
?>
the html:
<?php include("rotate.php"); ?>
<?php include("rotate.php"); ?>
<?php include("rotate.php"); ?>
*the random.txt just has a list of filenames with links.
Simple solution...
Get the array of random images (you already did this)
Shuffle the array
Pop an image off the end of the array whenever you need one
rotate.php
$random = "random.txt";
$fp = file($random);
shuffle($fb); //randomize the images
in your code
<?php include('rotate.php') ?>
Whenever you need an image
<?php echo array_pop( $fb ) ?>
http://php.net/manual/en/function.array-pop.php
function GetRandomItems($arr, $count)
{
$result = array();
$rcount = 0;
$arrsize = sizeof($arr);
for ($i = 0; ($i < $count) && ($i < $arrsize); $i++) {
$idx = mt_rand($rcount, $arrsize);
$result[$rcount] = trim($arr[$idx]);
$arr[$idx] = $arr[$rcount];
$rcount++;
}
return $result;
}
$listname = "random.txt";
$list = file($listname);
$random = GetRandomItems($list, 3);
echo implode("<BR>", $list);
P.S. Actually, Galen's answer is better. For some reason I forgot about shuffle xD
You can use array_rand() to select more than one random key at a time, like this:
$random = "random.txt";
$fp = file($random);
shuffle($fp);
// You don't need this. The array_rand() function
// is automatically seeded as of 4.2.0
// srand((double)microtime()*1000000);
$keys = array_rand($fp, 3);
for ($i = 0; $i < 3; $i++):
$rl = $fp[$keys[$i]];
echo $rl;
endfor;
This would eliminate the need for including the file multiple times. It can all be done at once.
You could write a recursive function to check if the array ID has already been printed, and if it has, call itself again. Just put that in a for loop to print three times :)
Though keep in mind that truly random images could overlap!
$beenDisplayed = array();
function dispRand($id) {
if (in_array($id, $beenDisplayed)) {
//generate random number
dispRand($id);
}
else {
array_push($beenDisplayed, $id);
}
}
for ($i = 0; $i < 3; $i++) {
dispRand($random_id);
}
<?
for ($i=0; $i<=9; $i++) {
$b=urlencode($cl[1][$i]);
$ara = array("http://anonymouse.org/cgi-bin/anon-www.cgi/", "http%3A%2F%2Fanonymouse.org%2Fcgi-bin%2Fanon-www.cgi%2F");
$degis = array("", "");
$t = str_replace($ara, $degis, $b);
$c="$t";
$base64=base64_encode($t);
$y=urldecode($t);
$u=base64_encode($y);
$qwe = "http://anonymouse.org/cgi-bin/anon-www.cgi/$y";
$ewq = "h.php?y=$u";
$bul = ($qwe);
$degistir = ($ewq);
$a =str_replace($bul, $degistir, $ic);
}
?>
when i put $cl[1][0], $cl[1][1], $cl[1][2] works successfull but when i put $i its returning null. why is this happening?
**I'm trying to change EACH url to base64 codes that I received from remote url with preg_match_all **
Have you checked that $c1[1] has 10 elements? (From $c1[1][0] to $c1[1][9] there are 10 elements, not 9.
Maybe you are getting null for the last one $c1[1][9]. Try to do a var_dump($c1[1]) to check that it contains all the elements that you expect.
Update:
Change the this line
for ($i=0; $i<=9; $i++) {
into this
for ($i=0; $i<9; $i++) {
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.