I just want to make a function like array_merge ( array $array1 [, array $... ] )
or simple function like myfunc($st1, $st2, $st3, $st4, $st5, etc)
function make_my_merge($) {
..... operation to be performed ......
}
Use func_get_args() to access all arguments (as an array) passed to the function. Additionally, you can use func_num_args() to get a count of all arguments passed in.
function make_my_merge () {
if ( func_num_args() ) {
$args = func_get_args();
echo join( ", ", $args );
}
}
// Foo, Bar
make_my_merge("Foo", "Bar");
// Foo, Bar, Fizz, Buzz
make_my_merge("Foo", "Bar", "Fizz", "Buzz");
Codepad: http://codepad.org/Dk7MD18I
Use func_get_args():
function make_my_merge() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
As can be seen, you get all arguments passed to your function via func_get_args() function which returns an array you can iterate over using each to work on each argument passed.
This should help: PHP Function Variable Arguments
You would never know how many arguments you want... So you cannot define exact function with unlimited arguments in my opimion. But what I suggest is passing 2 arguments in a function, one as number of index or values in array and other the array itself.... It goes something like this
<?php
$arr = array('val1','val2','val3',.....);
$count = count($arr);
$result = your_function($count,$arr);
?>
Your function would look like this which goes somewhere on the top or other php files or class
<?php
function your_function($count,$arr)
{
//Here you know the number of values you have in array as $count
//So you can use for loop or others to merge or for other operations
for($i=0;$i<$count;$i++)
{
//Some operation
}
}
?>
Related
I have a function which receives unlimited number of arguments.
(I am using func_get_args for that)
Example: function generate($one, $two, $three, ...)
Each one of the parameters represents a column in another array (let's call it $array).
I want to receive the value of the another array on $array[$one][$two][$three]
That means that the number of "[]" is unlimited
I have tried to generate a var in var for this.
<?php
$ron = array("sir" => "yes");
$name = 'ron["sir"]';
echo var_dump(${$name});
?>
My result:
Notice: Undefined variable: ron["sir"] in
C:\Users\ronr\Desktop\xampp\htdocs\lol.php on line 5 NULL
If you want to use the args as a path to array value, you can try this:
$result = $array;
$args = func_get_args();
foreach($args as $arg) {
$result = $result[$arg];
}
var_dump($result);
Actually, the error is correct, you are defining a variable named ron["sir"], something like this:
${'ron["sir"]'} = 'foobar';
echo ${'ron["sir"]'};
. To show the value of sir in the $ron array, it should be:
$ron = array("sir" => "yes");
$name = 'ron';
var_dump(${$name}["sir"]);
I have array, I want to make selection in it, but before do selection
I want to take 2 numbers in front of each values in array:
$myarray[2] = array(62343,62444,62343,08453,62333);
I want something like this:
$arraysubstr = substr($myarray[2],0,2)
if(($arraysubstr) < 62) //not work (work for first array value)
{
redirect
}else{
no problem
}
I thank all those who want to comment
You can use array_walk() function. It takes two parameters one is array and another is a function. You can perform any operation you want using the function on your array.
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");
Use array_walk() function to walk through the array. It returns true on success and false on failure. Its accepts two parameters one is array and other is callback fnction.
$myarray[2] = array(62343,62444,62343,08453,62333);
function func($value,$key) {
$item = substr($value,0,2);
if(($item) < 62)
{
echo 'redirect';
}else{
echo 'no problem';
}
}
array_walk($myarray[2], "func");
I am using an array in php that updates certain values in the array with the help of a function. The function works perfect but I want to apply the function to each element in an array in a increasing order.
Below is the function name.
CalculateDate($swappedarray,$row,$SetupTime);
The argument $row is the key number for each array element.
I want the function to do something like this.
CalculateDate($swappedarray,0,$SetupTime);
CalculateDate($swappedarray,1,$SetupTime);
CalculateDate($swappedarray,2,$SetupTime);
And so on until the last key number.
While the function works correct. I am just not able to use the for loop for doing this. The code for the 'for loop' which does not work and i tried is as follows.
for ($row = 0; $row <= $maxnum; $row++)
{
CalculateDate($swappedarray,$row,$SetupTime);
}
How can I make the function do what I need to do as explained above. Which is apply the function to each array key?
Would this work for your problem? (Substitute '$inputarray' for your starting array)
function some_callback($rowitem, $key, $userdata)
{
// echo $key;
CalculateDate($userdata[0], $key, $userdata[1);
}
array_walk($inputarray, 'some_callback', array($swappedarray, $SetupTime));
Basically, array walk is good for calling a function of your choice for each value in the array (similar to array_map, except array_walk makes it easier to pass additional arguments to the callback function).
In this code, we pass your $swappedarray and $SetupTime to the callback by putting them in an array. If $swappedarray does not change as you call CalculateData, it might be better to do the following to avoid recreating the same array:
function some_callback($rowitem, $key, $userdata)
{
// echo $key;
CalculateDate($userdata[0], $key, $userdata[1);
}
$walk_arguments = array($swappedarray, $SetupTime);
array_walk($inputarray, 'some_callback', array($swappedarray, $walk_arguments));
Let me know how it works out for you.
https://secure.php.net/manual/en/function.array-walk.php
https://secure.php.net/manual/en/function.array-map.php
I just passed the array name in the function argument as a reference and it worked.
CalculateDate(&$swappedarray,$row,$SetupTime);
I have this code:
function returnArray() {
$intData = array("1", "3");
return $intData[array_rand($intData)];
}
I'm trying to make a function similar to the one above.
Instead of adding integers with commas I'm trying to implode the commas with the integers.
Sort of like a dynamic version of the above using json_decode, file_get_contents, a foreach loop, array, array_rand & return
This is my code:
function Something() {
foreach (json_decode(file_get_contents('removed'), true) as $jsonArr) {
$arrData = array(implode(",", $jsonArr));
$roundData = $arrData[array_rand($arrData)];
return $roundData;
}
}
I was just wondering if I'm doing it right and if the array is correct or not.
Also it doesn't return anything from the array.
When I try to implode, it throws an error
implode invalid argument
It seems you're trying to print a random room_id from the JSON response.
The problem lies here:
$intData = array(implode(",", $arrRoomsReverse['room_id']));
You can't initialize an array like that.
Just push the room_id element to the array, like so:
$intData[] = $arrRoomsReverse['room_id'];
Now, you can simply get a random room_id outside the loop:
$intRoom = $intData[array_rand($intData)];
The function would look like:
function returnArray()
{
$str = file_get_contents('...');
$jsonArr = json_decode($str, true);
foreach ($jsonArr as $arrRoomsReverse)
{
$intData[] = $arrRoomsReverse['room_id'];
}
$intRoom = $intData[array_rand($intData)];
return $intRoom;
}
And to call the function:
echo returnArray();
I'm tryin to merge an array that I have when it is being created through a function
I have a function, and it returns an array.
class myarray
{
public function getAr($id)
{
// mysql query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
public function get3($id)
{
// mysl query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
}
How come I tried to merge together the array:
$get = new myarray();
while($row = $fet->fetch(PDO::FETCH_ASSOC))
{
$arrayAr = $get->getAr($id);
$array3 = $get->get3($id);
$new_array = array_merge($arrayAr ,$array3); //this gives me the error
print_r($arrayAr); //displays array
}
print_r($arrayAr); //displays nothing, why is that?
It says that its not an array?
array_merge() [function.array-merge]: Argument #1 is not an array
But I can print_r($arrayAr); and its like an array inside the while loop, but it doesn't display anything outside of it?
when I tried this...
$new_array = array_merge((array)$arrayAr ,(array)$array3);
It doesn't display an error, but it isn't merged either.
Help?
Thanks
You $arrayAr is local variable and 2nd print_r() is used beyond of scope of his variable. If you need it available wider, "declare" it before foreach, with i.e. $arrayAr = array(); (or whatever value you want - it is not important in this case, yet array() makes code clear).