I want to return an array from function but it return nothing. If i declare any string that return fines but i need to return.
class someclasss {
function somefunction {
$arr = array();
if(condition){
array_push($arr, array("name"=>"john"));
return $arr;
}
}
}
I tried to return an simple array also but that also didnt worked!
Can anyone help to know how to return an array from function??
Your current code has two problems:
It is not returning the variable that contains the array. It is returning the result of the array_push() function, which is probably not what you want.
It is only calling return when inside the conditional. If the conditional doesn't fire, no return statement is encountered. This essentially is equivalent to doing return null; if the condition doesn't fire.
You probably want something more like:
function somefunction {
$arr = array();
if(condition){
array_push($arr, array("name"=>"john"));
}
return $arr;
}
Which can be short-cutted to:
function somefunction {
return condition ? ['name' => 'john'] : [];
}
Related
i have got the following recursive function:
private function myRecursiveFunction()
{
$results = [];
//stuff related to $results
...
if(!$done){
.....
$this->myRecursiveFunction();
}
return $results;
}
when i do var_dump($results) inside function i got the all array results
but when i call the function from another one i will got only the first element in $results array.
public function myFunction()
{
$results = $this->myRecursiveFunction();
}
I am not 100% sure what you wish to accomplish here, but recursive functions usually send their "workload" all the way to the innermost function, then the results are "added" on each other at the way back. If this is indeed what you want, you may need to change your code to something like this:
private function myRecursiveFunction()
{
$results = [];
//stuff related to $results
...
if(!$done){
.....
// Add the computed results of the recursive call to our data stack
$results[] = $this->myRecursiveFunction();
}
// Return the entire result array
return $results;
}
<?php
$arr=array("b"=>4,"a"=>2,"c"=>8,"d"=>"6");
class Sort {
public $arr = array();
public function __construct(&$arr=array()) {
$this->arr = $arr;
}
static function my_sort($a,$b) {
//I am trying to cycle through the array $arr within this class
foreach ($this->arr as $key => $value) {
print "success";
}
if ($a==$b)
return 0;
return ($a<$b)?-1:1;
}
}
uasort($arr,array("Sort","my_sort"));
print_r($arr);
?>
I would like to cycle through the array $arr using foreach, while also within the sorting function my_sort, but I can't figure out how to properly reference the array. I set up a public constructor which references the array, but I'm unsure of how to interact with the array after it's been initialized.
imo there is 2 problems :
"importing" the array into you class: what you did is ok
$arr = array("b"=>4,"a"=>2,"c"=>8,"d"=>"6");
$sort = new Sort($arr);
Your array is now referenced in you class
sorting you array: add a sort() function to your class
public function sort()
{
return uasort($this->arr, array(__CLASS__, "my_sort"));
}
Use the function
$sort->sort();
PS: your my_sort function is wrong, it should not contain $this. Use another non static function to walk throw the array.
You can modify the sort() function ie:
public function sort()
{
foreach ($this->arr as $item) {
//stuff
}
return uasort($this->arr, array(__CLASS__, "my_sort"));
}
I have a function that returns a multidimensional array, but I also need to return a single value. I am currently using the single value via the global keyword, so I can modify it inside the function.
But I'm wondering if there is another/better way to return 2 values from a function?
Current (pseudo) code:
global $iNumber;
$arrResult;
{do some calculations and queries}
$iNumber = 73;
return $arrResult;
The function that called this function can use the array of arrays, and also the global variable which has been updated to 73.
But is there another/better way to combine or pass these two different values?
You can do it in two ways: to return an array or an object.
Array solution:
function calculate(...) {
//do some stuff
return ['result' => $arrResult, 'iNumber' => $iNumber];
}
Object solution:
function calculate(...) {
//do some stuff
$object = new stdClass();
$object->result = $arrResult;
$object->iNumber = $iNumber;
return $object;
}
stdClass is just an example and you can create your own class for this purpose.
You can make a class and use a class variable.
Something like this:
class Test
{
public $iNumber;
function __construct()
{
# code...
}
public function yourCal()
{
// you calculations
$this->setNumber(73);
return $arrayOfArrays;
}
public function getNumber()
{
return $this->iNumber;
}
public function setNumber($var)
{
$this->iNumber = $var;
}
}
// Use the class in another php file
include 'Test.php';
$test = new Test();
// do calculations
$arrayOfArrays = $test->yourCal();
// get the number
$iNumber = $test->getNumber();
echo $iNumber; // returns 73
print_r($arrayOfArrays); // print your array
I was coding and I stumbled into this. Why doesn't this code work?
function remove($array,$key) {
unset($array[$key]);
}
function finished() {
$finished = array(1,2,3,4,5);
remove($finished,3);
return $finished;
}
http://codepad.org/vemXHwnA
This is because the array is copied (as it is passed by value). You need to pass by reference if you want to alter the original variable. Note the & in the parameter list of remove. It indicates that the parameter is passed by reference:
function remove(&$array,$key) {
unset($array[$key]);
}
function finished() {
$finished = array(1,2,3,4,5);
remove($finished, 3);
return $finished;
}
Demo
You need to return the array from your function as changing it in there does not affect the array in the global scope.
function remove($array,$key) {
unset($array[$key]); // $array is only changed inside the function
return $array;
}
$array = remove($array, 'key'); // now $array is changed
pass the reference of that variable using &
function remove(&$array,$key) {
unset($array[$key]);
}
Alrighty, I'm getting quite frustrated, namely because I thought I had this issue solved, or had accomplished this successfully before.
Quick preliminary:
PHP 5.3.6.
Error reporting cranked to 11. (-1 actually; future safe, all errors/notices)
I have a class, it aggregates request parameters. For giggles here is a stripped down version:
class My_Request{
private $_data = array();
public function __construct(Array $params, Array $session){
$this->_data['params'] = $params;
$this->_data['session'] = $session;
}
public function &__get($key){
// arrg!
}
}
Anyways, the reason for arrg! is, no matter what I try, I always get an error whenever the $key doesn't exist. I've tried:
// doesn't work
$null = null;
if(isset($this->_data[$key])){ return $this->_data[$key]; }
return $null;
// doesn't work
return $this->_data[$key];
I've been told ternary operators cannot result in a reference, ergo, that of course doesn't work, but we know that from the if condition attempt anyways. What happens, for example:
// params will have foo => bar, and session hello => world
$myRequest = new My_Request(array('foo' => 'bar'), array('hello' => 'world'));
// throws an error - Undefined index: baz
echo $myRequest->params['baz'];
I'm losing my mind here; perhaps I hallucinated a scenario where I achieved this. Is it not possible to (without throwing a notice) successfully do this?
Clarification: Things I've tried
The aforementioned:
// no check, no anything, just try returning : fails
public function &__get($key){
return $this->_data[$key];
}
// null variable to pass back by reference : fails
public function &__get($key){
$null = null;
if(isset($this->_data[$key])){
return $this->_data[$key];
}
return $null;
}
Other attempts:
// can't work - can't return null by reference nor via ternary : fails
public function &__get($key){
return isset($this->_data[$key])
? $this->_data[$key]
: null;
}
echo $myRequest->params['baz'];
The isset check in your __get function will look up "params" from $this->_data and return the array. The notice you get is from outside the class and about a key "baz" in the returned array - which in your example was never actually defined.
I realize this question is stale, but I just stumbled on it via Google while looking for the answer (which I have since found).
class My_Request{
private $_data = array();
public function __construct(Array $params, Array $session){
$this->_data['params'] = $params;
$this->_data['session'] = $session;
}
public function &__get($key){
if (array_key_exists($key, $this->_data)) {
return &$this->_data[$key]; // Note the reference operator
} else {
$value = null; // First assign null to a variable
return $value; // Then return a reference to the variable
}
}
}
$this->_data[$key] is an operation that returns a value, so returning the value will result in an error because it's not a reference. To make it return a reference instead, you have to use the reference: &$this->_data[$key].
Haven't tried this because I avoid __get and __set, but maybe this would work for you:
public function __get($key){
if(!isset($this->_data[$key]))
return false;
return $this->_data[$key];
}
Totally untested, but it looks like it could maybe do the job.