PHP function won't execute when called - php

I'm having a problem with this function. It's supposed to echo out some stuff, but for some reason it won't do so when I call it.
Here's the function:
$count = count($info['level']);
function displayInfo()
{
for ($i=0; $i<$count; $i++)
{
echo "[b]".$info['name'][$i]."[/b]\n\n"
."Level: ".$info['level'][$i]
."\nPrice: ".$info['price'][$i]
."\nSellback: ".$info['sell'][$i]
."\nLocation: ".$location
."\n\nType: ".$info['type'][$i]
."\nElement: ".$info['element'][$i]
."\nDamage: ".$info['damage'][$i]
."\nBTH: ".$info['bth'][$i]
."\n\nSPECIAL"
."\nHits: ".$info['hits'][$i]
."\nType: ".$info['stype'][$i]
."\nElement: ".$info['selement'][$i]
."\nDamage: ".$info['sdamage'][$i]
."\nBTH: ".$info['sbth'][$i]
."\nRate: ".$info['rate'][$i]
."\n\nDescription\n".$description
."\n".$img
."\n\n\n";
}
}
And here's the code I use to call the function:
<?PHP
displayInfo();
?>
I can't find out what's wrong--it's not a sintax error, page loads without interuption.
Thanks in advance.

You are declaring the $count and $info variable outside of your function :
// $info already exists
$count = count($info['level']); // and $count is initialized here
function displayInfo()
{
for ($i=0; $i<$count; $i++)
...
In PHP, a variable declared outside of a function is not visible from inside the function.
If you want your "external" variables to be visible from inside the function, you have to declare them as global in the function :
$count = count($info['level']);
function displayInfo()
{
global $count, $info;
// $count is now visible ; same for $info
for ($i=0; $i<$count; $i++)
...
But it's generally considered better to pass the variables as parameters to the function : you have to declare them as a parameter :
function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
...
And pass them to the function when calling it :
$count = count(...);
displayInfo($count, $info);
Passing parameters instead of using global variables ensures you know what your functions have access to -- and modify.
Edit : thanks for the note, X-Istence ! Didn't read enough of the given code :-(

$count and $info are declared outside the function and therefore they are not visible within it. You could pass $info into the function and then calculate $count within, like this:
//get info from db, or somewhere
$info = array();
displayInfo($info);
function displayInfo($info)
{
$count = count($info['level']);
//now $count and $info are visible.
}
See http://php.net/manual/en/language.variables.scope.php

Add global for variables which should be accessed from function, but are not parameters:
function displayInfo()
{
## bad design
global $count, $info;
...
Or pass your array as parameter:
function displayInfo($info)
{
## this is local variable accessable only inside function
$count = count($info['level']);
...
}
The call it
<?php
## don't forget to pass array as parameter
displayInfo($info);
?>

You can either move your $count inside the function, or pass it to the function. Also, your $info array has to be passed into the function as well, or made a global. Here is the function prototype with count and info being passed into the function.
function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
{
// Do stuff
}
}
<?php
$count = count($info['level']);
displayInfo($count, $info);
?>

Indeed, there were no syntax errors, but there were other errors, as was pointed out in other reactions. I highly recommend configuring PHP to show all errors when writing new code. This way you would've seen a notice about $info and $count not being defined inside your function.
You can turn errors on in a couple of ways.
Configure your server to do it.
Turn them on by using an .htaccess file
Use the following PHP code in the very beginning of your script.
Example:
error_reporting(E_ALL | E_NOTICE); //turn on all errors
ini_set("display_errors","On"); //activate display_error

Related

PHP array inside an included page within a loop

I have a PHP page which returns an array. I have included the PHP page inside a loop in a different PHP page. I am getting the results of only the first array. It is printing nothing when i try to print the array after first iteration.
Page1:
Start of loop
include Page2
End of loop
Page2:
return array
result
printing only the first value in array
foreach($res->list as $Flist){
Field($k,$fi);
}
Page1:
function Field($key, $Id){
include('inp.php');
print_r($S_array);
}
Page2: (inp.php)
$Deficit = f1();
for($i = 0; $i<20 ; $i++){
$S_array[$i] = $Deficit;
}
function f1(){
return $something;
}
You need to remove the f1() function definition from inp.php. Otherwise, you get a fatal error due to trying to redefine the function each time you include it. Move its definition into Page 1, or some other file that you just include once.
But a better way to design the whole thing is to only define functions in your include files, and call them from the other files.
inp.php:
function get_S_Array() {
$Deficit = f1();
for ($i = 0; $i < 20; $i++) {
$S_array[$i] = $Deficit;
}
return $S_array;
}
function f1() {
return $something;
}
page 1:
include('inp.php');
function Field($key, $Id){
$S_array = get_S_array();
print_r($S_array);
}

Why isn't this example of call by reference not working?

I am clearing the concept of call-by-reference.Can anyone please explain the code lines below shown as an example of call-by-reference?
<?php
function test(){
$result = 10;
return $result;
}
function reference_test(&$result){
return $result;
}
reference_test($result);
?>
You have two problems.
$result is never set and the test function is never called.
You do a pass by reference on the wrong function. A pass by reference is to change the variable inside and outside the function.
Here is the solution, changed the function a bit to show you the difference. You don't need to return the variable you changed by reference.
// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){
$result = 10;
$nochange = 10;
}
// Just returns result
function reference_test($result){
return $result;
}
$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0

Problems with saving value of superglobal in PHP

This code doesn't work:
$john = array("goodie");
function test(){
global $john;
for($i=0; $i<100; $i++)
{
array_push($john, "pro");
}
print_r($john);
}
test(); // outputs correct array: array("goodie","pro","pro"....)
/* then when again function is called */
test(); // output is NULL
// with 100 errors in loop:
// expects parameter 1 to be an array, NULL given...
I have problems to fix this in my code, and I don't understand problem. Why instead adding new 100 items in array, global variable is unset.
I think you shouldn't use your globals in that way. A function should be a closed part of your code. So its much better to make an input parameter and work with the variable like that.
function test(array $input) {
for($i=0; $i<100; $i++) {
array_push($input, "pro");
}
return $input;
}
This is one reason why global variables are generally evil. Because its global, it's probably getting modified somewhere, possibly in some obscure fashion that's hard to detect. Instead of making it global, why not pass it in as a parameter and return it back out?
function test(array $param){
for($i=0; $i<100; $i++)
{
array_push($param, "pro");
}
return $param;
}
$john = array();
$john = test($john);
// ...
$john = test($john);

Array as parameter (PHP) : Error :Undefined variable

I'm trying to call a function and pass an array and other variables to it. this is the code I use to do that :
function fnGetElementsById($ArrCols, $tableName, $id) {
while($arrCols[$i])
{
if($i != 0)
{
$sql = $sql.',';
}
$sql = $sql.$arrCols[$i].' ';
$i++;
} }
the while line is the error or notice line and when I test with var_dump, the array is empty.
the calling code :
$arrCols = array(
0=>'marque',
1=>'prix'
);
$CDB->fnGetElementsById($arrCols, 'Portables', $_POST['id1']);
thank you
You haven't defined $i before the while loop is invoked. Therefore you are basically trying this:
while($arrCols[null]) {
Also your parameter is $ArrCols and the variable name in the while conditional is $arrCols (lowercase first letter).
You need to fix both of these.
You have a case issue.
function fnGetElementsById($ArrCols, $tableName, $id) {
while($arrCols[$i])
Should be
function fnGetElementsById($arrCols, $tableName, $id) {
while($arrCols[$i])
Notice change from ArrCols to arrCols.
Also you did not initialize your $i variable.
Please set it to 0 before using.

how can i make a function see a variable outside it

How can I place a variable inside a function when it is run in order to preg_match the right information. Here is my existing code:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
What I am attempting to do is pull the $username variable from outside the function and allow it to be seen within it so I can pull the right matches in my while loop. While the previous comes back blank, if i do the following it works:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
Modify the function to take the $username variable as a parameter:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
Then call it like:
$username = "test";
is_txt($file, $username);
Alternatively, you can use the global keyword to make the variable visible from the function. This is sometimes useful, but shouldn't be used all over the place. See the variable scope manual entry for more info.
You need to import the var with global:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
But passing the value in as a parameter as explained by Jonah is a better solution in most cases.

Categories