Running a loop that has a function inside it - php

I have a problem trying to run a code inside the loop, my loop consist of a function.
Here is my coding:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
function myfunction($value) {
//Do something
}
echo $val;
}
The problem is the code outputs only the 1st value in my array. I am very confused, am I not suppose to declare a function inside the loop?

Your code ends up with Fatal error, since at the second iteration it tries to redeclare function myfunction. That's why it is printing only first value of array.
In order to avoid that fatal error you can check if that function has been already defined using function_exists() function like this:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}
PHP is a scripting language and it is syntactically correct to declare a function inside for loop or inside if statement, but it is a bad practice and can cause a lot of errors afterwards.
The best way is to declare a function outside loop, and, if needed, call it from within a loop like this:
<?php
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($value); //may you was intended to pass $val here?
echo $val;
}

Don't declare the function inside the loop, declare it before the loop and then call to it inside the loop with myFunction($value);

the function should be in a separate procedure
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($val)
echo $val;
}
then this is your function
function myfunction($value)
{
//Do something
}

Declare the function outside of the loop
either return a value from the function, or let the function output data
For example:
function myfunction($value) {
//Do something
echo $value;
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++) {
myfunction($new[$i]);
}

I am assuming you want to print out the first 4 elements of the array.
do something like this
function myfunction() {
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
echo $val;
}
}
myfunction();

You should declare the function outside the loop
function myfunction($value) {
return ($value + 25); // an example
}
$new = array(1,2,3,4);
for($i = 0; $i < count($new); $i++){
echo myfunction($new[$i]);
}
Also you should set the loop from 0 to the end of the array, so if you'll have more than 4 entries in the array the code should be ok

You can declare an anonymous function instead:
for ($i=0; $i<=3; $i++) {
// code
$myFunction = function($value) { /* code */ }
$myFunction($val);
// code
}

that is not the right way to do it...
first declare the function outside the loop, then call the function in the loop
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
myfunction( $val); //call function where u wanted... here (in your case)
echo $val;
}

You are not suposed to declare the function inside a loop...

Related

Function with array called multiple times inside other function

I have one function called several times inside other function. Something like that:
function function_one()
{
global $get, $count;
function_two ();
$ok1 = $get[0];
function_two ();
$ok2 = $get[1];
function_two ();
$ok3 = $get[2];
}
In the “function_two()”, I have the variable “$get” who is set as an array, and I have a counter, something like that:
function function_two()
{
global $get, $count;
// something here
$get = array();
if (isset($count))
{
$count = $count;
} else {
$count = 0;
}
$get[$count] = $some_value;
$count ++;
}
The problem: only the “$ok3” are full, the others came empty. Please help me!
I'm assuming that the 2nd function is function two (You put function one) the issue is the
$get=array();
This resets the get array to empty (all of it)
I would delete the line and move the $get=array(); to your main function before all of this is called. Or you can move it into the top of function one (the real function one)
It appears your function_one() in the second comment is actually function_two(). Your problem is here:
$get = array();
You format the $get variable as an empty array every time you call the function. Anyhow, don't use globals. Instead create a class with variables and use parameters.
class Count {
public $get = array();
function_two($count) {
$this->get[$count] = $some_value;
$count++;
return $count;
}
function get() {
return $this->get;
}
}

php global variable and instance variable utilization

I'm having hard time accomplishing one simple task. I have a method that would generate random number and depending on the outcome assign specific outcome to an array variable. What i want to do is get that array variable through instance method which would be called from the other class.
<?php
class MyClass
{
public $results = array(array());
public function simulated_games()
{
$game_series1=array(23,34,56);
$game_series2=array(31,42,67);
$iter_wins=array(array());
for($i=0; $i<10;$i++)
{
$random = rand(0,100);
for($b=0; $b<1;$b++)
{
if($random <= $game_series1[0])
{
$iter_wins[$i][$b]=3;
}
else if($random <= $game_series2[0]+$game_series2[1])
{
$iter_wins[$i][$b]=1;
}
}
}
$results=$iter_wins;
}
>here i create method just to return variable
public function get_simulated_games()
{
return $this->results;
}
}
<?php
$a= new MyClass();
$a->simulated_games();
$array = array();
>here is the issue, it return just 1, but supposed to return range numbers
$array=$a->get_simulated_games();
for($f=0; $f<sizeof($array);$f++)
{
for($g=0; $g<5;$g++)
{
echo $array[$f][$g];
}
echo '<br>';
}
?>
You have the error in results.
You modify interal function variable which is not set instead of class variable
change
$results=$iter_wins;
to
$this->results=$iter_wins;

Use Array From Function 1 in Function 2

I have a (simplified) function that uses in_array() to check if a value is in an array:
function is($input) {
$class = array('msie','ie','ie9');
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
I want to break this into two separate functions, where the first defines the array:
function myarray() {
$class = array('msie','ie','ie9');
}
and the second runs the check—either like this:
function is($input) {
myarray();
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
Or this:
function is($input) {
global $class;
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
But both of the above cause this error:
Warning: in_array() [function.in-array]: Wrong datatype for second argument in /home/vanetten/temp.ryanve.com/PHP/airve.php on line 73
What is the proper way use an array from one function in another? Can an array be a global variable? How do I make this work? Is it more efficient to use a global variable or to call the first function within the second function. Any help is definitely appreciated.
Return the array from the first function:
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
return in_array($input, $array);
// or even just
// return in_array($input, myarray());
}
function is($input) {
$class = myarray();
$is = false;
...
Easiest way (which also negates the use of global variables, which is a bad practice since using $class somewhere else down the line may result in unexpected behavior) is something like
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
$is = FALSE;
if (in_array($input, $array)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
In this example, we just make myarray() return the needed array. In is(), add the line $array = myarray(), which will save the array from myarray(), so it is useable from is() as the alias $array. Then simply change $class to $array, and it should work fine.

PHP/JS: Removing final comma in a delimited list

What is the best, most concise coding practice for eliminating the final comma when generating a comma-delimted list in a typical for loop? This comes up ALL THE TIME and I cannot stand writing so many extra lines of code for something so simple... there must be a better technique/pattern.
foreach ($list as $item)
{
echo "'".$item . "',";
}
What is the best way (using PHP and/or JS) to make the above code produce a comma everywhere but the last iteration?
Right now I am doing something like this:
$total = count($images);
$i=0;
foreach ($list as $item)
{
$i++;
echo "'".$item."'";
if ($i<$total) echo ',';
}
But this adds FOUR LINES OF CODE for something so simple...
The Standard PHP Library (SPL) offers a handy class, CachingIterator that can be used to see if there are any more items to be iterated over. The following may not be as concise as you would like but it is flexible (i.e. can be used for far more than just arrays).
$array = range('a', 'g');
$cache = new CachingIterator(new ArrayIterator($array));
foreach ($cache as $item) {
echo "'$item'";
if ($cache->hasNext()) {
echo ',';
}
}
The above example outputs
'a','b','c','d','e','f','g'
In case you didn't simplified the code example:
echo implode(',', $list);
does it (see also implode PHP Manual ).
If there is more code within the foreach loop you need to keep track whether or not you're on the last element and deal with the situation:
$count = count($list);
$current = 0;
foreach ($list as $item)
{
$current++;
$notLast = $current !== $count;
echo $item;
if ($notLast) echo ',';
}
Edit: you added a similar code to the question after I answered this, so if that is too burdensome for your coding fingers and especially (and understandable) you don't want to repeat such code all day long the same, you need to encapsulate it for re-use. One solution is to implement this within a re-useable iterator:
$list = array('a', 'b', 'c');
class PositionKnowingIterator implements iterator
{
/**
* #var iterator
*/
private $inner;
private $count;
private $index;
public function __construct(array $list) {
// NOTE: implement more iterators / objects to deal with in here
// if you like. This constructor limits it to arrays but
// more is possible.
$this->count = count($list);
$this->inner = new ArrayIterator($list);
}
/* SPL iterator implementation */
public function current() {
return $this->inner->current();
}
public function next() {
$this->index++;
$this->inner->next();
}
public function key() {
$this->inner->key();
}
public function rewind() {
$this->index = 1;
$this->inner->rewind();
}
public function valid() {
return $this->inner->valid();
}
/* Position Knowing */
public function isLast() {
return $this->index === $this->count;
}
public function notLast() {
return !$this->isLast();
}
public function isFirst() {
return $this->index === 1;
}
public function notFirst() {
return !$this->isFirst();
}
public function isInside() {
return $this->notFirst() && $this->notLast();
}
}
foreach($iterator = new PositionKnowingIterator($list) as $item)
{
echo "'".$item."'", $iterator->notLast() ? ',' : '';
}
echo implode(",", $list);
without using foreach needed
User implode() function to achieve this. Sometimes it's also necessary to put something around, for example, to quote SQL fields' values:
$fields = '"' . join('", "', $values) . '"';
And for JavaScript use Array.join() method (W3C):
var implodedString = someArray.join(',')
if I get you right, you can use the implode function.
This does the job for you.
BR,
TJ
Why not:
echo implode(",", $list);
?
The common used practice: using 'join' function or its analog. This function exists almost in every language, so it's most simple, clear and environment independent approach.
echo join(", ", $list);

how to travel through the array in php?

i am having one key list
for example
$key_list=array("list"=>array("task","duration"));
function array_key_fun($key_list,$test_input){
//(is_array($test_input)){
return array_map('myfunction',$test_input,$key_list);
//}
}
//$va=array_map("myfunction",$test_input);
//print_r(array_key_fun($key_list,$test_input));
function myfunction($arr)
{
if(is_array($arr))
{
$get_array= get_childs($arr);
return $get_array;
}
}
function get_childs($arr){
$newarr=array();
$newarr_en='';
foreach($arr as $key=>$value)
{
if(is_array($value)){
$newarr[$key]=get_childs($value);
}else{
if (in_array($key,$key_list)) //here im facing the problem with key_list
{
..............
}
else
{
...............
}
}
}
return $newarr;
}
Either pass in function or declare as global
function abc($a,$key_list){
OR
function abc($a){
global $key_list;
//rest of code
EDIT:
When you pass the array as parameter of function you have to pass the value in call as well
when you call this function this should be
//array should be declared before calling function
$key_list=array("list"=>array("task","duration"));
abc($a,$key_list); //pass this array
http://php.net/manual/en/function.array-walk.php
array_walk
try this
You have to bring the variable into scope, within your code you have ......... if you replace that with global $key_list this will allow the function to Read / Write to that stack.

Categories