Let's say I have a function returning the following array:
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
And I'd like to assign the third and forth array elements to a variables without using of temporary variable:
list(NULL,NULL,$banana,$pear) = fruits();
This code will not work, but it will show the idea of the way I'd like to use list construction.
The reasons I'd like to use list is the following:
I use PHP 5.3 so construction like fruits()[2] will not work.
I can do more assigns within one line of fairly readable code
I'd like to skip temporary variables to reduce code size and increase its readability.
So is there any possibility to use list and skip some array elements?
php 5.5.14
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
list(,,$banana,$pear) = fruits();
echo $banana; // banana
Yes, you can skip elements: just omit the variable name:
list(,,$banana,$pear) = fruits();
PHP 7.1+
[,,$banana,$pear] = fruits();
Related
I have created a session array as
$_SESSION[yans]=array();
I wish to initialize first 5 elements of this to 0.How it can be done?
As every on suggested above, try this:-
<?php
session_start();
$_SESSION['yans'] = array('A','B','C','D','E');
echo "<pre/>";print_r($_SESSION);die;
?>
Output:- http://prntscr.com/7btkxv
Note:- it's a simple example given for your understanding. thanks.
You can use the array_fill function to achieve this:
$_SESSION['yans'] = array_fill(0, 5, 0);
You should also remember to quote the yans, otherwise PHP will raise a NOTICE (unless yans is actually a defined constant).
$arr[0]=123;
$a="arr[0]";
echo $$a;
gives me error
Notice: Undefined variable: arr[0]
on the last line.
What should I do to make it work?
EDIT:
Above is the simplification of what I want to do. If someone wants to know why I want to do this, then here's the explanation:
This is something like what I want to do:
if(condition){
$a=$arr1[0][0];
$b=$arr1[0][1];
$c=$arr1[0][2];
}
else{
$a=$arr2[0];
$b=$arr2[1];
$c=$arr2[2];
}
I can compact it like this:
if(condition)
$arr=$arr1[0];
else
$arr=$arr2;
$a=$arr[0];
$a=$arr[1];
$a=$arr[2];
But I wanted to try doing this using variable variable:
if(condition)
$arr="$arr1[0]";
else
$arr="$arr2";
$a={$$arr}[0];
$b={$$arr}[1];
$c={$$arr}[2];
Sure, we don't need variable variables as we can still code without them. I want to know, for learning PHP, why the code won't work.
Now that you said what you’re actually trying to accomplish: Your code doesn’t work because if you look at $arr1[0][0], only arr is the variable name; the [0] are special accessors for certain types like strings or arrays.
With variable variables you can only specify the name but not any accessor or other operation:
A variable variable takes the value of a variable and treats that as the name of a variable.
Your solution with the additional variable holding the array to access later on would be the best solution to your problem.
What you are trying to do just won't work - the code $arr[0] is referencing a variable called $arr, and then applying the array-access operator ([$key]) to get the element with key 0. There is no variable called $arr[0], so you cannot reference it with variable-variables any more than you could the expression $foo + 1 .
The real question is why you want to do this; variable variables are generally a sign of very messy code, and probably some poor choices of data structure. For instance, if you need to select one of a set of variables based on some input, you probably want a hash, and to look up an item using $hash[$item] or similar. If you need something more complex, a switch statement can often cover the cases you actually need.
If for some reason you really need to allow an arbitrary expression like $arr[0] as input and evaluate it at runtime, you could use eval(), but be very very careful of where the input is coming from, as this can be a very easy way of introducing security holes into your code.
FROM PHP DOC
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Use
echo ${$a}[0]; // 123
Edit : Based on your edit you can simply have
list($a, $b, $c) = (condition) ? $arr1[0] : $arr2;
Or
$array = (condition) ? $arr1[0] : $arr2;
$a = $array[0];
$b = $array[1];
$c = $array[2];
As pointed out you don't need variable variables. To get a PHP variable variable name containing index (a key) use array_keys() or array_search() or other array parsers. From php's site:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
You could also use the following (using $var= instead of echo):
$arr[0]=123;
$arr[1]=456;
foreach ($arr as $key => $value) {
echo "arr[{$key}] = {$value} \r\n";
}
Which outputs:
arr[0] = 123
arr[1] = 456
But I don't see why you'd do that, since the whole point of the array is not doing that kind of stuff.
ok, So I have this array:
$choices = array($_POST['choices']);
and this outputs, when using var_dump():
array(1) { [0]=> string(5) "apple,pear,banana" }
What I need is the value of those to become variables as well as adding in value as the string.
so, I need the output to be:
$apple = "apple";
$pear = "pear";
$banana = "banana";
The value of the array could change so the variables have to be created depending on what is in that array.
I would appreciate all help. Cheers
Mark
How about
$choices = explode(',', $_POST['choices']);
foreach ($choices as $choice){
$$choice = $choice;
}
$str = "apple,pear,pineapple";
$strArr = explode(',' , $str);
foreach ($strArr as $val) {
$$val = $val;
}
var_dump($apple);
This would satisfy your requirement. However, here comes the problem, since you could not predefine how many variables are there and what are they, it's hard for you to use them correctly. Test "isset($VAR)" before using $VAR seems to be the only safe way.
You'd better just split the source string in just one array and just operate the elements of the specific array.
I have to concur with all the other answers that this is a very bad idea, but each of the existing answers uses a somewhat roundabout method to achieve it.
PHP provides a function, extract, to extract variables from an array into the current scope. You can use that in this case like so (using explode and array_combine to turn your input into an associative array first):
$choices = $_POST['choices'] ?: ""; // The ?: "" makes this safe even if there's no input
$choiceArr = explode(',', $choices); // Break the string down to a simple array
$choiceAssoc = array_combine($choiceArr, $choiceArr); // Then convert that to an associative array, with the keys being the same as the values
extract($choiceAssoc, EXTR_SKIP); // Extract the variables to the current scope - using EXTR_SKIP tells the function *not* to overwrite any variables that already exist, as a security measure
echo $banana; // You now have direct access to those variables
For more information on why this is a bad approach to take, see the discussion on the now deprecated register_globals setting. In short though, it makes it much, much easier to write insecure code.
Often called "split" in other langauges, in PHP, you'd want to use explode.
EDIT: ACTUALLY, what you want to do sounds... dangerous. It's possible (and was an old "feature" of PHP) but it's strongly discourage. I'd suggest just exploding them and making their values the keys of an associative array instead:
$choices_assoc = explode(',', $_POST['choices']);
foreach ($choices as $choice) {
$choices_assoc[$choice] = $choice;
}
Which is more efficient for clearing all values in an array? The first one would require me to use that function each time in the loop of the second example.
foreach ($array as $i => $value) {
unset($array[$i]);
}
Or this
foreach($blah_blah as $blah) {
$foo = array();
//do something
$foo = null;
}
I don't want to use unset() because that deletes the variable.
Like Zack said in the comments below you are able to simply re-instantiate it using
$foo = array(); // $foo is still here
If you want something more powerful use unset since it also will clear $foo from the symbol table, if you need the array later on just instantiate it again.
unset($foo); // $foo is gone
$foo = array(); // $foo is here again
If we are talking about very large tables I'd probably recommend
$foo = null;
unset($foo);
since that also would clear the memory a bit better. That behavior (GC) is however not very constant and may change over PHP versions. Bear in mind that re-instantiating a structure is not the same as emptying it.
If you just want to reset a variable to an empty array, you can simply reinitialize it:
$foo = array();
Note that this will maintain any references to it:
$foo = array(1,2,3);
$bar = &$foo;
// ...
$foo = array(); // clear array
var_dump($bar); // array(0) { } -- bar was cleared too!
If you want to break any references to it, unset it first:
$foo = array(1,2,3);
$bar = &$foo;
// ...
unset($foo); // break references
$foo = array(); // re-initialize to empty array
var_dump($bar); // array(3) { 1, 2, 3 } -- $bar is unchanged
Unsetting the variable is a nice way, unless you need the reference of the original array!
To make clear what I mean:
If you have a function wich uses the reference of the array, for example a sorting function like
function special_sort_my_array(&$array)
{
$temporary_list = create_assoziative_special_list_out_of_array($array);
sort_my_list($temporary_list);
unset($array);
foreach($temporary_list as $k => $v)
{
$array[$k] = $v;
}
}
it is not working! Be careful here, unset deletes the reference, so the variable $array is created again and filled correctly, but the values are not accessable from outside the function.
So if you have references, you need to use $array = array() instead of unset, even if it is less clean and understandable.
I'd say the first, if the array is associative. If not, use a for loop:
for ($i = 0; $i < count($array); $i++) { unset($array[$i]); }
Although if possible, using
$array = array();
To reset the array to an empty array is preferable.
Isn't unset() good enough?
unset($array);
How about $array_name = array(); ?
Use array_splice to empty an array and retain the reference:
array_splice($myArray, 0);
i have used unset() to clear the array but i have come to realize that unset() will render the array null hence the need to re-declare the array like for example
<?php
$arr = array();
array_push($arr , "foo");
unset($arr); // this will set the array to null hence you need the line below or redeclaring it.
$arr = array();
// do what ever you want here
?>
Maybe simple, economic way (less signs to use)...
$array = [];
We can read in php manual :
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
I see this questions is realla old, but for that problem I wrote a recursive function to unset all values in an array. Recursive because its possible that values from the given array are also an array. So that works for me:
function empty_array(& $complete_array) {
foreach($complete_array as $ckey => $cvalue)
{
if (!is_array($cvalue)) {
$complete_array[$ckey] = "";
} else {
empty_array( $complete_array[$ckey]);
}
}
return $complete_array;
}
So with that i get the array with all keys and sub-arrays, but empty values.
The unset function is useful when the garbage collector is doing its rounds while not having a lunch break;
however unset function simply destroys the variable reference to the data, the data still exists in memory and PHP sees the memory as in use despite no longer having a pointer to it.
Solution:
Assign null to your variables to clear the data, at least until the garbage collector gets a hold of it.
$var = null;
and then unset it in similar way!
unset($var);
The question is not really answered by the posts. Keeping the keys and clearing the values is the focus of the question.
foreach($resultMasterCleaned['header'] as $ekey => $eval) {
$resultMasterCleaned[$key][$eval] = "";
}
As in the case of a two dimensional array holding CSV values and to blank out a particular row. Looping through seems the only way.
[] is nearly 30% faster then as array()
similar as pushing new element to array
$array[] = $newElement then array_push($array, $newElement)
(keep in mind array_push is slower only for single or 2 new elements)
Reason is we skip overhead function to call those
PHP array vs [ ] in method and variable declaration
Is it possible to sanitize all input sent by one method in PHP by simply doing
$var = mysql_real_escape_string($_POST);
and then access elements of $var as I would have of $_POST ?
I don't think you can call mysql_real_escape_string on an array.
But this would work
$cleanData = array_map('mysql_real_escape_string', $_POST);
array_map works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result.
Like superUntitled, I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array_map to achieve the same result.
As a side note, I would recommend using a function to sanitize your results:
function escape($txt) {
if (get_magic_quotes_gpc())
$txt = stripslashes($txt);
if (!is_numeric($txt))
$txt = "'" . mysql_real_escape_string($txt) . "'";
return $txt;
}
this function will remove html tags from anything you pass to it
function strip_html(&$a){
if(is_array($a)){
foreach($a as $k=>$v){
$a[$k]=preg_replace('/<[^<]+?>/','',$v);
}
}else{
$a=preg_replace('/<[^<]+?>/','',$a);
}
return;
}
What I find handy is to encapsulate the request data (Post, Get, Cookie etc) in to an Object and then to add a filter method which u can pass an array of function names to. This way you can use it like this:
$array = array('trim','mysql_real_escape_string');
$request->filter($array);
Body of the method works using a loop an array_map like in Mark's example. I wouldn't run the mysql_real_escape_string over my entire $_POST though, only on the necessary fields ( the ones that are getting queried or inserted )
#Shadow:
Array_Map will work with single dimension array but it wont work with multi-dimension arrays.
So, this will work.
$cleanData = array_map('mysql_real_escape_string', $_POST);
but if that $_POST array were to have another array, like this:
$array = $_POST['myArray']['secondArray'];
If you have an array such as above, array map will throw an error when you try to run a function that only takes a String as an argument, because it wont be handle to an array when its expecting just a string.
The solution provided on the below page is much more handy, and does it recursively for every element inside the array.
PHP -Sanitize values of a array