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"]);
Related
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 have a form, and the URL is like this:
http://hostname/projectname/classname/methodname/variablename
And in my JavaScript, I fill an array like this:
var currentrelations = new Array();
$(".ioAddRelation").each(function(index) {
currentrelations[index] = $(this).html();
});
And this array has two values ['eeeeee','eeeeee']
So the url is:
http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee
And in my PHP, in the class InformationObject, on the method addIO:
public function addIO($currentRelations =null) {
$name = $_POST['name'];
$type = $_POST['type'];
$concept = $_POST['concept'];
$contents = $_POST['contents'];
$this->model->addIO($name, $type, $concept, $contents);
if (isset($_POST['otherIOs'])) {
$otherIOs = $_POST['otherIOs'];
$this->model->addOtherIOs($name, $otherIOs);
}
$NumArguments = func_num_args();
if ($currentRelations!=null) {
$IOs = $_POST['concetedIOs'];
$this->model->setIoRelations($name,$IOs, $currentRelations);
}
exit;
include_once 'Successful.php';
$s = new Successful();
$s->index("you add the io good");
}
But when I print the array $currentRelations using this statement:
echo count($currentRelations)
The results was 1 not 2, and when I print the first element using thie statement echo $currentRelations[0] I get e not eeeeee
why is that? What is the solution? What am I doing wrong?
As I commented, the $currentRalations is a string, so using count on any type which is not an array or an object will return 1.
Also, note that when you do this $currentRelations[0] on a string, you are accessing a character in the zero-based index of the string. As strings are arrays of characters you can use the square array brackets to access specific chars within strings. This is why echo $currentRelations[0]; printed e in your code.
To split a string you should use the explode function like this:
$curRel = explode(',', $currentRelations);
and then see what you get
var_dump($curRel);
Hope it helps.
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
}
}
?>
I have the following array:
$data['standard'][36][2] = 52.5;
$data['standard'][42][2] = 57.5;
$data['standard'][48][2] = 62.5;
$data['standard'][54][2] = 67.5;
$data['standard'][60][2] = 72.5;
$data['standard'][36][3] = 60.5;
$data['standard'][42][3] = 65.5;
$data['standard'][48][3] = 70.5;
$data['standard'][54][3] = 75.5;
$data['standard'][60][3] = 80.5;
$data['standard'][72][3] = 90.5;
i'm trying to return the keys of the third index where the first two match. e.g. for 'standard' and 48 need an array(2,3)
but for 'standard' and 72 i would return array(3)
Also I'm wondering if I should store this data in xml or something similar?
Try this:
$result = array_keys($data['standard'][48];
This just returns the keys of the $data['standard'][48] array: 2 and 3.
You can use something like this:
function findInArray(&$data,$param1,$param2)
{
return isset($data[$param1][$param2]) ? array_keys($data[$param1][$param2]) : array();
}
Example:
$keys = findInArray($data,"standard",48); // array(2,3);
$keys = findInArray($data,"standard",72); // array(3);
It is fine to use an array for storing data, if this is easier for you to handle.
How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php