PHP array inside an included page within a loop - php

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);
}

Related

Why array is not updated when i want to print it out (print_r)?

<!DOCTYPE html>
<html>
<body>
<?php
$array_task=array();
fillArray($array_task);
function fillArray($array){
$array1=array();
$array2=array();
for ($i=0;$i<8;$i++){
$array1[$i]=$i+1;
$array2[$i]=rand(0,100);
}
$array=array_combine($array1,$array2);
echo"Array before any editions <br>";
print_r($array);
echo"<br>Array after adding sum and multiplication <br>";
addSumMulti($array);
print_r($array);
echo"<br>Array after adding last element after each array element <br>";
#addAfterEach($array);
}
function addSumMulti($array){
$sum=0;
$multiplication=1;
for ($i=1;$i<=10;$i++){
$sum+=$array[$i];
if ($i==3 || $i==4){
$multiplication*=$array[$i];
}
}
$array[9]=$sum;
$array[10]=$multiplication;
print_r($array);
echo "<br>";
}
?>
</body>
</html>
first print_r ($array) shows 8elements, then in the next function i add 2 elements. And print_r in the function addSumMulti shows 10 elements, but print_r after function addSumMulti inside the fillArray shows only 8 elements. What is wrong, what should I change so that i could see 10 elements in print_r after addSumMulti (21 line)?
In PHP ordinary variables are passed by value*. So, when you pass your array to your function a new copy is made which your function code manipulates. Your function doesn't return any values, so the new values of your array are lost, and the calling code sees only the original copy of the array.
There are two ways to make the changes to the original array:
return a value from the function. e.g.:
function addLine($arr) {
$arr[] = "Additional Line";
return $arr
}
$arr = ["First line"];
$arr = addLine($arr);
or pass in the variable by reference. E.g:
function addLine(&$arr) {
$arr[] = "Additional Line";
return $arr
}
$arr = ["First line"];
addLine($arr);
See Variable scope and Passing By Reference
*Objects are always passed by reference
Your $array has not been updated due to variable scope.
$array declared inside fillArray() cannot be referenced in another function. To do so It should be global variable.
Either modify the function addSumMulti to return an array and use the same in fillArray OR make $array as a global variable.
Option 1:
function fillArray($array){
.....
$arrayAfterSum = addSumMulti($array);
.....
}
function addSumMulti($array){
.....
.....
return $array;
}
Option 2:
$array = array(); // its a gloabal variable
function fillArray($array){
global $array; // in order to access global inside function
.....
.....
}
function addSumMulti($array){
global $array; // in order to access global inside function
.....
.....
}

PHP - Check if a function contains

I want to check if a function contains a variable called $marker.
This is what I'm trying to do:
if(function('head') contains '$marker') {
return true;
}
Is there any way to do this?
Ummm... it's not built into PHP, and, frankly, changing the files would be better, but for science reasons, I wrote a check for it. It fetches the filenames's contents every function call, so I'd recommend, if you use it more than once, to store the file's contents in another variable, but, nevertheless, this is will give you a functional view on how to do it:
<?php
function test() { $marker;}
function negativeTest() {
$noMarker;
}
function checkFunction($function, $variable, $filename) {
$file = file_get_contents($filename);
preg_match_all("/function\s+([a-z0-9_-]+)\s*\(.*?\)\s*\{((\n|.)*?)\}/im",$file,$matches);
for ($i = 0; $i < count($matches[1]); $i++) {
if ($matches[1][$i] == $function && strpos($matches[2][$i], $variable) != false) {
return true;
}
}
return false;
}
echo checkFunction("test","\$marker","index.php");
?>

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);

Recursive function acts weird in php

I got stuck when I learned about recursive functions in PHP. I know recursive function are those which are being called by itself. My code is:
function addition_no($x,$y) {
if($x==0) {
return $x;
}
return addition_no($x+$y);
}
echo addition_no(1,2);
When I tried executing this code I get:
Warning: Missing argument 2 for addition_no(), called in
/web/com/13978781902261/main.php on line 6 and defined in
/web/com/13978781902261/main.php on line 2
What i need is to add two numbers via recursion.
I created this code in order to summarize values in an array using recursivity is:
<?php
//values to add
$add = array(5,4,4,6,7);
function addval($add,$pos) {
if($pos == 0) {
return $add[0];
}
else {
return $add[$pos] + addval($add,$pos-1);
}
}
//last position in vector
$last_position = count($add)-1;
echo addval($add, $last_position);
?>
You can try this
return addition_no($x,$y);
You have to check any condition for recursive function otherwise it will be infinite recursion..
The warning is appropriate as you call the function inside it self with a different argument structure.
Try the factorial recursive function to learn how it works:
<?php
// Initiating Recursion
echo factorial(5);
//Recursive Function Definition with 1 parameter
function factorial($number)
{
//Break condition for recursion
if($number==1)
return $number;
//Fetch and Stack Recursion
return $number*factorial($number-1);
}
So, you get the basic recursion, in simple English, as :
factorial(n) = n x factorial(n-1) = n x (n-1) x factorial(n-2)
For You particular case, you actually don't need a recursion as your arguments are not relying on the previous argument result. However, for the sake of learning, you can do something like this:
<?php
//Summation
function summation($x) {
if($x==0) {
return $x;
}
return $x+summation($x-1);
}
echo summation(5);
//Summation with 2 step
function summation($x,$y) {
if($x<1) {
return $x;
}
return $x+summation($x-$y,$y);
}
echo summation(5,2);

PHP function won't execute when called

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

Categories