PHP adressing multdimensional arrays with an array or a string? - php

The question is whether it's possible to address a multidimensional array with a string or another array.
Say we have:
$a['key1']['key2'] = "value"
//and
$keyArray = array('key1', 'key2')
//or
$keyString = 'key1,key2'
Is it possible to do something like:
$a[$keyArray]
//or
$a[keyString]
which would then give me back the value "value"?
Obviously, what I wrote doesn't work (not on my system, at least), but is something similar possible and if yes, how?
Thanks.

As far as I'm aware this isn't possible. However I feel like http://php.net/manual/en/class.arrayiterator.php might be help you answer your question

If you want a one liner:
$a['key1']['key2'] = "value";
$keyArray = array('key1', 'key2');
$value=$a;foreach ($keyArray as $key) $value=$value[$key];
echo $value;
You should note that this obviously doesn't check if the keys exist.

Obviously you cannot pass two indices using some string or one array value. But if you need to use it that way then one way around can be like:
$a['key1']['key2'] = "value"
$keyArray = array('key1', 'key2');
$a[$keyArray[0]][$keyArray[1]]//'value'
That's just in case you are somehow receiving key values in $keyArray and you can access $a only through that otherwise direct access is most convenient:
$a['key1']['key2']//'value'
I hope it helps

Related

Best practice for clearing an array

I have an array that I would like to clear the values out of and I'm wondering what the best way to accomplish this is.
I tried setting it to nothing:
$array = array();
... later on
$array = "";
Afterwards I'll add new values to it later:
foreach($something as $thing):
$array[] = $thing['item'];
endforeach;
And it seems to have done what I needed it too. But after a quick search online I'm seeing a lot of recommendations to do the following instead:
unset($array);
$array = array();
Is there any difference between this action and the one I performed up top?
Setting $array to "" sets your variable to a string value, and unset removes the variable. Since you are just trying to clear the array, then $array = array() should be good enough.
I believe that array() explicitly defines it as an array. Your first statement $array = "" sets it to an empty string. Using unset will "reset" the variable, so it's neither a string or array until you assign a value to it, and $array = array() simply defines it as a new blank array.

how to get single result from nested foreach

I have a problem I've been trying to solve for two weeks now, please I need help on this. I do not understand using array well so please bear with me.
I'm trying to combine two arrays and store them in one array so I did this.
$oldvalue =$_SESSION[oldmids]; //value example aa=1,bb=2,cc=3;
$newvalue =$_SESSION[newmids]; //value example 001,002,003;
$result =array();
foreach($oldvalue as $oldval){
$kk =explode('=',$oldval);//i want to keep my tagging so
$oldtag =$kk[0]; // I use explode.
foreach($newvalue as $newid){
$kk =$oldtag.$newid;
$result[] =$kk;
}
}
// print_r($result);
my goal here is to keep my old tag and replace with numeric value, I don't have a problem with
the output, but I only need to get a unique value from my array $result. I tried using array_unique, but failed. Is this the right approach?
I'm not exactly sure what you are trying to do, but I think that array_push() is what you want:
http://www.php.net/array_push
This is my best guess:
$oldvalue =$_SESSION[oldmids]; //value example aa=1,bb=2,cc=3;
$newvalue =$_SESSION[newmids]; //value example 001,002,003;
$result = array();
foreach($oldvalue as $oldval){
$kk =explode('=',$oldval);//i want to keep my tagging so
$oldtag =$kk[0]; // i use explode.
foreach($newvalue as $newid){
$kk =$oldtag.$newid;
array_push($result, $kk);
}
}
print_r($result);

Most efficient way to empty an array

I have an array containing several keys, values, objects etc.. I need to empty that array but I'd like to do it in the most efficient manner.
The best I can come up with is:
foreach ($array as $key => $val) unset($array[$key]);
But I don't like the idea of having to loop through the array to just empty it.. surely there's a nice slick/clever way of doing this without wasting memory creating a new array?
Note: I'm not sure myself if it does cost extra memory in creating the array as new again. If it doesn't then $array = new array(); would be a fine way of 'emptying' it.
Just try with:
$array = array();
It highly depends on what you mean.
To empty the current reference you can always do
$array = array();
To completely remove the current instance from the scope
unset($array);
Unfortunately both of these cases don't necessarily mean the memory associated with each element is released.
PHP works with something called "references" for your variables. Your variables are actually labels or references pointing to data, not the actual container for data.
The PHP garbage collector can offer more insight on this subject.
Now take a look at this example, taken from the docs:
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );# a: (refcount=3, is_ref=0)='new string'
unset( $b, $c );
xdebug_debug_zval( 'a' );# a: (refcount=1, is_ref=0)='new string'
This unfortunately applies to all your variables. Including arrays. Cleaning up the memory associated with the array is a whole different subject I'm afraid.
I've noticed a longer discussion in the comments regarding using unset() on each individual key.
This feels like extremely bad practice. Consider the following code:
class A{
function __construct($name){$this->name=$name;}
function __destruct(){echo $this->name;}
}
$a=array();
$b=array();
$c=array();
for($i=0;$i<5;$i++) {
$a[]=new A('a');
$b[]=new A('b');
$c[]=new A('c');
}
unset($a);
$b=array();
echo PHP_EOL.'done'.PHP_EOL;
This will output:
aaaaabbbbb
done
ccccc
When the reference to a particular data structure reaches 0, it is cleaned from memory.
Both =array() and unset will do the same thing.
Now if you don't actually need array() you can use null :
$array=null;
This keeps the label in memory, but removes the reference it held to any particular data.
It's simple:
$array = array();
$array will be existing and type of array (but empty), and your data can be garbaged later from memory.
Well... why not: $array = array(); ?
As Suresh Kamrushi pointed out, I could use array_keys:
foreach (array_keys($array) as $key) unset($array[$key]);
This is probably the nicest solution for now.. but I'm sure someone will come up with something better soon :)
Try this:
// $array is your original array
$array = array_combine( array_keys( $array ), array_fill( 0, count($array), 0 ) );
The above will blank your array keeping the keys intact.
Hope this helps.

PHP - Save value AND name using $_POST

I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}

PHP key value pairs vs. arrays

I'm trying to pass key values pairs within PHP:
// "initialize"
private $variables;
// append
$this->variables[] = array ( $key = $value)
// parse
foreach ( $variables as $key => $value ) {
//..
}
But it seems that new arrays are added instead of appending the key/value, nor does the iteration work as expect. Please let me know what the proper way is.
Solution
$this->variables[$key] = $value;
did the trick - the iteration worked as described above.
I think you may be looking for:
$this->variables[$key] = $value;
The way you have it right now you are creating an array of arrays, so you would have to do this:
foreach($this->variables as $tuple) {
list($key, $value) = $tuple;
}
Referring to Perl, but helps understand the difference between hashes and arrays:
Some people think that hashes are like arrays (the old name 'associative array' also indicates this, and in some other languages, such as PHP, there is no difference between arrays and hashes.), but there are two major differences between arrays and hashes. Arrays are ordered, and you access an element of an array using its numerical index. Hashes are un-ordered and you access a value using a key which is a string.
Source: http://perlmaven.com/perl-hashes

Categories