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.
Related
function report_test() {
$color = "blue";
$name = "John";
mobile_test($color, $name);
echo $columnid;
}
function mobile_test($color, $name) {
-snipped Insert MySQL Query-
$columnid = 5;
return $columnid;
}
Hopefully the example above portrays what I'm attempting to do. Globalising the variable columnid isn't an option in this scenario due to other various reasons. I also do not want to alter the mobile_test($color, $name) function. I find that if I echo the function instead the MySQL Insert Query is ran twice, meaning two sets of the same results gets entered into the database.
Is there another way to do this?
I assume that you want to echo out the return value from mobile_test() inside of report_test(). The easiest way to do this is to simply echo out $columnid inisde of mobile_test(). When you call mobile_test() from report_test(), the echo statement will be called as well, and the value will be outputted:
function mobile_test($color, $name) {
...
$columnid = 5;
echo $columnid;
return $columnid;
}
There's also the possibility to make use of PHP's short tag syntax (as <?= mobile_test(); ?>), assuming you want to echo the return of the function directly, and not do anything else with it.
Note that if you leave in the return value (return $columnid;), you'll be able to use this value directly as a comparison in the report_test() function:
if (mobile_test($color, $name) === 5) {
echo "The column ID is 5" /* This line will be triggered */
}
You may do this:
function report_test() {
$color = "blue";
$name = "John";
$columnid = mobile_test($color, $name);
echo $columnid;
}
you need to store the returned value from mobile_test() as a new variable. This won't need to change the mobile_test()
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 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;
?>
In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).
I initialize a php array named $present, the purpose of this array is to hold the value of 1 if a name is present or zero if the name is absent. i have a name array of size 10. below is the code mentioned, but it is not working.
$present = Array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
i have also tried this :
$present = Array();
for($i=0;$i<=10;$i++){
if(empty($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
please help thanks!
I think this may be what you are looking for. You're missing the $i when setting it to 1.
$present = array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
Should be:
$present = Array();
for($i=0;$i<10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
I'm not sure exactly what you're trying to do here, but if you just want to keep track of whether a name is present or not, you could just make $present be an array of names, and then use in_array.
$present = array('John', 'Paul', 'George');
echo in_array('John', $present); # returns 1
echo in_array('MacArthur', $present); #returns 0