PHP and Array_round spiteful function - php

I'm trying to create a function to pick up words from a text file randomly, and no one here poblema. The problem arises when I try to verify if the user correctly inserts the words. Unfortunately, I always get a negative answer. From what I understood when called, the function can not save the contents into the variable that naturally remains empty.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
echo $word[$randomword];
}
}
$a = random_word();
echo "-----------------";
echo $a;
?>
If I try to check the $a variable it tells me that it is NULL. I'm sure the problem is the function but I know PHP shortly and I'm struggling to find the error.

You need to return something. Not sure if you want to return a string or an array but your code seems to be made for string.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
$returner .= $word[$randomword] . " ";
}
return trim($returner);
}
$a = random_word();
echo "-----------------";
echo $a;
?>

Related

How to convert $_SESSION['myarray'] to regular PHP array

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']);
?>

Issues with variable scopes in PHP

I have just written a program to check for the variable scopes in PHP. The code goes like this:
<?php
$value = 1;
function change_value(){
if(some_condition){
$value = 0;
$asset = 1;
}else{
$asset = 0;
}
return $asset;
}
echo $value;
change_value();
echo $value;
?>
Now, the output of the above program is 11.
How can I change the value of $value once it enters the function change_value() ?
Pass the parameter by reference:
<?php
$value = 1;
function change_value(&$value){
if(/* some_condition */){
$value = 0;
$asset = 1;
}else{
$asset = 0;
}
return $asset;
}
echo $value; // echoes 1
$asset = change_value($value);
echo $value; // echoes 0
echo $asset; // echoes 0 or 1 depending on /* some_condition */
?>
Please don't use global ... even if some suggest it.
It's bad. It let's the variable be accessable from all over the script and you will be very confused when you come upon the situation where you access $value in a different script you included and it acts different then...
What you're trying to do, goes against common principles, but.
$GLOBALS['value'] = 0;
Using this inside function will let you change that value, but I suggest you not to do this.
The way others have outlined, is far more right.

How to put random number in array and showing this array in php

Recently I made a program to create 4 random numbers I want to put these numbers in an array but I did not echo the array's numbers :
my code is:
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[i] = rand_num_generator();
}
echo $number[2];
?>
Here i am not able to access array using their index values.
You missed the $ sign in front of the i inside $number[i] which must be used before a variable
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
//print_r($number);to see the whole array
You only echo once: at echo $number[i];, $i is 4, hence you only display the last random number.
You could loop on your array to echo each.
Put your echo into loop. And you have some mistakes. Use that:
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
To put something in an array I recommend to use array_push
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
array_push($numbers, rand_num_generator());
}
print_r($numbers); //Or use 'echo $numbers[0] . " " . $numbers[1]' etc etc
?>

Whats wrong with this array sorting

Here is my code :
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b-1);$i++)
{
for($j=1;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
I just want to know what's wrong in the above code ? because if i take 3 array values it works fine but for 4 its not working....can someone do the modification for the same code,and also please briefly explain why is it not working any issues with looping?I am not looking for different code.
You have mistakenly modified the bubble sort algorithm. Use standard one.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++) //Changes over here
{
for($j=0;$j<($b);$j++) //Changes over here
{
if($a[$j]>$a[$i]) //Changes over here
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
Why are you manually sorting when you have sort?
$a = array(10,8,6,5);
sort($a);
var_dump($a);
Similarly, why are you using temporary variables when you have list?
list($a[$i],$a[$j]) = array($a[$j],$a[$i]);
try below code may be that will help.
<?php
function pr($array = array())
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$a = array(10,8,6,5);
$b = count($a);
for($i=0;$i <= ($b-1);$i++)
{
for($j=0; $j < ($b);$j++)
{
if($a[$j] < $a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
pr($temp);
pr($a);
?>
<?php
$a=array(8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++)
{
for($j=0;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
The inner loop doesn't need to be executed n times (where n=number of elements to be sorted). Every time the outer loop executes, one more element at the end (for ascending order) is in the correct position. So, inner loop should not check those elements.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++){
for($j=0;$j<($b-$i);$j++){ // this change will save time
if($a[$j]>$a[$i]){
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
?>

continued : unable to post fields to the next page in php and HTML

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.

Categories