PHP Function pulling an array that matches the parameter - php

$youtubes = array("lNT4H39G2rw","pF2_qvdm8DQ","_8ytwhhJwco","K16ZRFWR2Mc","9WuPxe7zc6Q","rXZIIclPnd0","J8ZwyN6E3_Q","OEWJbsh0z-4","o62-X0stdFM","aIIiww2Neq0","5TJc-VbNYg0","MYQa1Tgw_z8","alxzFm-bqug","UmI7oyllrlY","RGKFXDHFmn4");
function randomFromArray($data) {
global $$data;
echo $$data[rand(0,count($youtubes)-1)];
}
randomFromArray("youtubes");
I am trying to get this to work as a function, so I can enter the array name as a parameter. It is then supposed to echo a random entry from the array. The bit where it gets the random entry from array works on its own if I substitute it straight in, but I can't seem to get it working as a function.
Any help?

You're using the variable name $youtubes in your randomFromArray function in the call to count (but the variable is not available under that name there).
Btw., why don't you pass in (a reference to) the array instead of its name? Would be much tidier than using global $$data; The following code uses a reference to avoid copying the array (but remember that then, the outside array could be changed from inside the method):
$youtubes = // ...
function randomFromArray(&$data) {
echo $data[rand(0,count($data)-1)];
}
randomFromArray($youtubes);

dont call the function randomFromArray("youtubes"); in this way you call the function with youtubes parametar like a string. and inside the function itself you dont have a $youtubes variable. call the function like this randomFromArray($youtubes);
hope this would help

You are passing the string 'youtubes' into the function, not the array. You want to pass in the name of the array:
randomFromArray($youtubes);

$youtubes = array("lNT4H39G2rw","pF2_qvdm8DQ","_8ytwhhJwco","K16ZRFWR2Mc","9WuPxe7zc6Q","rXZIIclPnd0","J8ZwyN6E3_Q","OEWJbsh0z-4","o62-X0stdFM","aIIiww2Neq0","5TJc-VbNYg0","MYQa1Tgw_z8","alxzFm-bqug","UmI7oyllrlY","RGKFXDHFmn4");
function randomFromArray($data) {
echo $data[rand(0,count($data)-1)];
}
randomFromArray($youtubes);

There are some things fundamentally wrong here.
global $$data
Why is there a double $ sign? And where would this data be coming from?
echo $$data[rand(0,count($youtubes)-1)];
Your function doesn't know the variable $youtubes, since you have never defined it inside of the function. All your function knows is the $data variable that you are passing to it.
randomFromArray("youtubes"); You are passing a string to your function, rather then your array. You probably want this instead:
randomFromArray($youtubes); // Pointing to your actual array, rather then a string
Try reading up on PHP functions first before attempting to use them as you're lacking a lot of basic knowledge about them.

After you put a ; after global $$data, you can try this: $f = $$data; and then echo $f[rand(..)]; if you really want to use names instead variables as others suggested. And if you do that you can use the string (or $f) further in the function code.

Related

PHP problem with array_push(mainArr, subAssociativeArr) inside a function

the array_push(mainArr, subAssociativeArr) does not work when it is inside a function. I need some help with this code:
$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');
function addOne($store, $element){
array_push($store, $element);
}
addOne($store, $samsung);
var_dump($store); //output: empty array
however it works fine if without function; like the following:
$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');
array_push($store, $samsung);
var_dump($store); //output: array is added
so, what is the problem???
You forgot to return
function addOne($store, $element){
$store[]=$element;
return $store;
}
$store = addOne($store, $samsung);
You could also pass by reference if you want to (which is more in line with the code you have):
function addOne(&$store, $element){
$store[]=$element;
}
addOne($store, $samsung);
Note the &. Instead of copying the inputs, this is more like a pointer to the original variable, so you can update it directly. Ether way is fine here, it's a matter of developers choice really. For example it can be very easy to mix the two:
//Don't do this
function addOne(&$store, $element){ //returns null
$store[]=$element;
}
$store = addOne($store, $samsung); //sets $store to null
Which you probably don't want to do, so I can see an argument for both ways. Unless you have super big array, it probably doesn't matter much. It's very easy to forget that a random function is pass by reference.
So use whatever method makes more sense to you.
P.S. - I refuse to use array_push, it's ugly and I don't like it :). Doing $store[]=$element; is the same as array_push($store,$element), except it avoids an unnecessary function call.
Cheers.
When it's in a function, you have a different scope. While the parameters to your addOne function have the same name, they are actually copies of the variables passed, not references to them.
So when you array_push() in a function, you're only affecting the variables in that function's scope, not the outer scope.
You can either return $store, or pass the variables by reference.
If you want it to work within a function you need a reference to the variable. A reference in PHP is defined as & and they are similar to "pointers" in C or C++.
Try this:
function addOne(&$store, $element){
array_push($store, $element);
}
addOne($store, $samsung);
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
http://www.php.net/manual/en/language.oop5.references.php

Pass variable of a function in the function call

So I am writing this php function which reads a csv file and assigns every column to a variable. In the end it needs to calculate the mean of a row. I would like to pass the row (from which the mean has to calculated) in the parameters.
My question is how do I pass a variable name (including the dollar sign) of a variable of the function?
I've tried several things like:
function("$number") //this just says the variable is undefined, which is true
Same as above, but without the quotes, does the same thing of course...
function("\$number")
Not entirely sure what you're trying to do, but it sounds something like variable variables. So, if you have a variable $foo you would pass it like this: myfunc('foo'); Then myfunc might look something like this:
myfunc($var) {
global $$var;
// do stuff with $$var
}
You'd probably be better off just loading the columns into an array and looping over that in the function.
If I understood correctly, what you need is a variable variable:
$some = 'foo';
$name = 'some';
echo $$name; //displays 'foo'

PHP array element calling a function?! $a=$b['c']($d,$e,$f);

Could someone please explain what is going on here in this code?
I can see it is an array called b accessing an element with the key 'c', but the stuff in the brackets? I don't know what is going on here.
$a=$b['c']($d,$e,$f);
$b['c'] must be a function name.
try to print it, you'll see.
$a=$b['c']($d,$e,$f);
calls that function passing $d, $e and $f arguments to it.
Try :
<?php
$func = 'var_dump';
$foo = array(1,2,3);
$func($foo)
It looks like you are looking at a variable function.
The expression above first evaluates the associative array $a=$b['c'] and then calls the function with that name, passing the arguments $d,$e,$f.
From the description:
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to, and
will attempt to execute it. Among other things, this can be used to
implement callbacks, function tables, and so forth.
It seems element at key c is expected to be a function.
In PHP5, you can use this kind of short notations. The function will be called with parameters d e and f.

Using function as array variables in PHP

Most of the time, when there is a function named func1 and it returns an array, I use this method to access a specific index of that returned array:
$myarray=func1();
echo $myarray['AssIndex'];
Is there a way to access it in a single line? Something like this?
// the brackets are not working. this is only to make my meaning clear.
echo {func1}['AssIndex'];
As of PHP 5.4, you can do this:
echo func1()['AssIndex'];
This is called Function Array Dereferencing.

Is there a version of the PHP array that is pass-by-reference?

I'm asking this because I'm working with a recursive function that generates a large array tree and the pass-by-copy aspect of the arrays are completely screwing with my head. I've tried using ArrayObject, but that's really an object, isn't it? None of the array_keys type array functions work with it, and json_encode doesn't understand that it's an array.
I'd like a version of the PHP array that feels, smells and looks like the normal array, but is pass-by-reference. Is there anything like that in PHP?
Woah woah hold up people; I'm well aware of the & symbol but that's what I'm trying to avoid. As my question specifies (^) I'm looking for a version of the PHP array that is pass-by-reference by default
I'd like a version of the PHP array that feels, smells and looks like
the normal array, but is pass-by-reference. Is there anything like
that in PHP?
No, There is nothing like that in PHP.
Json encode should be able to pass objects. But if you for some reason NEED an array, you can't use objects and then cast it as array before encoding to json?
<?php
$object = (object)array("number"=>1);
function addToTen($object){
if($object->number<10){
$object->number++;
addToTen($object);
}
}
addToTen($object);
echo json_encode((array)$object);
//echoes {"number":10} with or without casting it as an array
?>
You could also wrap your array in an object of course, like this:
$object = new stdClass;
$object->a = array();
function fillUpArray($object){
if(count($object->a)<10){
$object->a[] = "someValue";
fillUpArray($object);
}
}
fillUpArray($object);
echo json_encode($object->a);
//echoes ["someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue"]
I must admit though I don't entirely get what you're trying to accomplish here :S
Yes, see the PHP manual page: http://php.net/manual/en/language.references.pass.php
Stop using &references altogether, in php they get cumbersome pretty quickly, (being, unlike C pointers, almost transparent, the only way to check you're actually using a reference is by assigning junk to it and check the effect this has on a tree) and you don't seem willing to handle that level of subtlety.
(Nor to wrap it with an ArrayObject, apparently)
Are you aware objects ARE references?
Object-wrap every aspect of your tree and your life will instantly get less miserable.
I am not aware of any such built-in functionality in PHP that you ask. Also, you are quite reluctant to use references. Hmmm...you could send a request to the PHP dev team to include such stuff in PHP v6, along with unicode that is supposed to come, that would us all happy :).
However, can you use a class and assign your initial array to one of the class variables and then process it and get it back after the recursion. Not sure if that would work, but anyway here it is:
<?php
class noReference {
public $myData;
public function __construct( $data ) {
$this->myData = $data; // this is your initial array.
}
// this function works on the myData array and changes it.
public function myRecursiveFunction() {
// your code here
$this->myRecursiveFunction(); // called as per your logic
// your code here
}
public function getData() {
return $this->myData;
}
public function __destruct() {
unset( $this->myData );
}
}
$data = array(/*WHATEVER_PLEASES_YOU*/);
$noref = new noReference( $data );
// this will be your recuresive function
$noref->myRecursiveFunction();
//your data here
$result = $noref->getData();
?>
Let me know if this works. Cheers!
you can force php to pass things by reference by adding an &-sign to the parameter. read the documentation for more information.

Categories