I want to unset first value of member array variable of a class but I'm not able to:
<?php
class A
{
public function fun()
{
$this->arr[0] = "hello";
}
public $arr;
}
$a = new A();
$a->fun();
$var ="arr";
unset($a->$var[0]); //does not unset "hello" value
print_r($a);
I could not find any solution after searching in Google. How can I remove the first value dynamically?
Try the following:
unset($a->{$var}[0]);
The problem with your code is, PHP tries to access the member variable $var[0] (which is null) and not $var.
You can try with array_shift:
array_shift($a->{$var});
This function uses reference to the value and removes (and returns) value from the beginning of your array.
<?php
class A
{
public function fun()
{
$this->arr[0] = "hello";
}
public $arr;
}
$a = new A();
$a->fun();
// no need to take $var here
// you can directly access $arr property wihth object of class
/*$var ="arr";*/
// check the difference here
unset($a->arr[0]); //unset "hello" value
print_r($a);
?>
TRY THIS
since $arr is a member of the class A and declared public, you can directly use
$a = new A();
$a->fun();
unset $a->arr[0];
But you will be surprised that for numeric indexed arrays, unset may bring problems.
suppose your array is like that;
$arr = ["zero","one","two","three","four"];
unset($arr[2]); // now you removed "two"
echo $arr[3]; // echoes three
Now array is ["zero","one", undefined ,"three","four"];
$arr[2] does not exist, it is undefined, and the rest is not reindexed...
for numeric indexed arrays using the method below is better:
$arr = ["zero","one","two","three","four"];
array_splice($arr,2,1); // now you removed "two" and reindexed the array
echo $arr[3]; // echoes four...
Now array is ["zero","one","three","four"];
Related
I have this function that doesn't work.
$b is an outside string that should bond with $a array that should return a group of strings.
$a=array('this','is');
function chkEdt($a,$b) {
$a[]=$b;
};
print_r($a);
Result -> array();
Why?
You need to make it a reference parameter.
function chkEdt(&$a,$b) {
$a[]=$b;
};
Then any changes to $a in the function will affect the array variable that's used as the argument.
Your example never actually calls the chkEdt function, and that function never returns anything.
Aside from that, variables have different scope inside and outside functions - even though they share a name, they are considered to be different variables because one of them is inside a function. Read https://php.net/manual/en/language.variables.scope.php for more detail.
You can either pass the variable by reference as in Barmar's answer, or you can make the function return a value and then re-assign the $a outside the function to the value returned by the function - like this:
$a = array('this','is');
function chkEdt($a,$b) {
$a[] = $b;
return $a;
};
$a = chkEdt($a, "a");
print_r($a);
Live demo: http://sandbox.onlinephpfunctions.com/code/00d19028b3909ca415b81e93c26a6ede9188c743
To clarify the difference, you could re-write the function with a different variable name within the function, and get the same result:
$a = array('this','is');
function chkEdt($z,$b) {
$z[] = $b;
return $z;
};
$a = chkEdt($a, "a");
print_r($a);
If I have an stdObject say, $a.
Sure there's no problem to assign a new property, $a,
$a->new_property = $xyz;
But then I want to remove it, so unset is of no help here.
So,
$a->new_property = null;
is kind of it. But is there a more 'elegant' way?
unset($a->new_property);
This works for array elements, variables, and object attributes.
Example:
$a = new stdClass();
$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))
unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())
This also works specially if you are looping over an object.
unset($object[$key])
Update
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by #CXJ . In that case you can use brackets instead
unset($object->{$key})
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Set an element to null just set the value of the element to null the element still exists
unset an element means remove the element
it works for array, stdClass objects user defined classes and also for any variable
<?php
$a = new stdClass();
$a->one = 1;
$a->two = 2;
var_export($a);
unset($a->one);
var_export($a);
class myClass
{
public $one = 1;
public $two = 2;
}
$instance = new myClass();
var_export($instance);
unset($instance->one);
var_export($instance);
$anyvariable = 'anyValue';
var_export($anyvariable);
unset($anyvariable);
var_export($anyvariable);
I'm curious if I can assign a variable the value of a specific array index value returned by a function in PHP on one line.
Right now I have a function that returns an associative array and I do what I want in two lines.
$var = myFunction($param1, $param2);
$var = $var['specificIndex'];
without adding a parameter that determines what the return type is, is there a way to do this in one line?
In PHP 5.4, you can do this: $var = myFunction(param1, param2)['specificIndex'];.
Another option is to know the order of the array, and use list(). Note that list only works with numeric arrays.
For example:
function myFunction($a, $b){
// CODE
return array(12, 16);
}
list(,$b) = myFunction(1,2); // $b is now 16
You could add an additional optional parameter and, if set, would return that value. See the following code:
function myFunction($param1, $param2, $returnVal = "")
{
$arr = array();
// your code here
if ($returnVal)
{
return $arr[$returnval];
}
else
{
return $arr;
}
}
If I have an stdObject say, $a.
Sure there's no problem to assign a new property, $a,
$a->new_property = $xyz;
But then I want to remove it, so unset is of no help here.
So,
$a->new_property = null;
is kind of it. But is there a more 'elegant' way?
unset($a->new_property);
This works for array elements, variables, and object attributes.
Example:
$a = new stdClass();
$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))
unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())
This also works specially if you are looping over an object.
unset($object[$key])
Update
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by #CXJ . In that case you can use brackets instead
unset($object->{$key})
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Set an element to null just set the value of the element to null the element still exists
unset an element means remove the element
it works for array, stdClass objects user defined classes and also for any variable
<?php
$a = new stdClass();
$a->one = 1;
$a->two = 2;
var_export($a);
unset($a->one);
var_export($a);
class myClass
{
public $one = 1;
public $two = 2;
}
$instance = new myClass();
var_export($instance);
unset($instance->one);
var_export($instance);
$anyvariable = 'anyValue';
var_export($anyvariable);
unset($anyvariable);
var_export($anyvariable);
Returning by reference is useful when
you want to use a function to find to
which variable a reference should be
bound. Do not use return-by-reference
to increase performance. The engine
will automatically optimize this on
its own. Only return references when
you have a valid technical reason to
do so.
whats does the bolded mean?
does it refer to something like
public function &getHellos() {
$sql = 'SELECT id, greeting FROM #__hello';
$data = $this->_getList($sql);
return $data;
}
where i am not binding to any variable?
We return by reference when we want the function GetRef() to decide which variable, $foo or $bar, the reference $foo_or_bar should be bound:
$foo = "foo";
$bar = "bar";
function &GetRef(){
global $foo, $bar;
if(rand(0, 1) === 1){
return $foo;
}else{
return $bar;
}
}
$foo_or_bar =& GetRef();
$foo_or_bar = 'some other value';
var_dump($foo); // either one of this will be 'some other value'
var_dump($bar); // either one of this will be 'some other value'
Derick Ethans also elaborated on this in "References in PHP: An In-Depth Look":
This [returning by reference] is useful, for example, if you want to
select a variable for modification with a function, such as selecting
an array element or a node in a tree structure.
Example code demonstrating selecting array element via return-by-reference:
function &SelectArrayElement(&$array, $key){
return $array[$key];
}
$array = array(0, 1, 2);
$element =& SelectArrayElement($array, 0);
$element = 10;
var_dump($array); // array(10, 1, 2)
Na. You can't pass a reference to a function name.
When passing a variable by reference, if you change it's value in your function, it's value will also be changed outside of the function.
For example :
function test(&$var) {
$var = strtolower($var);
}
function second_test($var) {
$var = strtolower($var);
}
$var = 'PHP';
second_test($var);
echo $var;
echo "\r\n";
test($var);
echo $var;
This will display :
PHP
php
As the second_test method doesn't have the variable passed by reference, it's updated value is only updated inside the function.
But the test method as the variable passed by reference. So it's value will be updated inside and outside of this function.
I believe it's referring to byref arguments not functions. For example this:
function doStuff(&$value1, &$value2) {
...
}
is an acceptable use of byref because the doStuff() function has to return 2 values. If it only doStuff() only needed to affect one value, it would be more elegant to have the function return it, by value, of course.
The bolded part means it's useful if you want to keep a reference to a variable, instead of the value of this variable.
The example about returning references, on php.net, explains it pretty well, IMO.