Lets say i have this code:
$val = 1;
$arr = Array();
$arr['val'] =& $val;
$val = 2;
echo $arr['val'];
This will print out 2, because $val was passed to $arr by reference.
My question is : if i passed a value to an array by reference, is there a way to remove that reference later on, making it a simple copied value ?
To make it clearer, i would like something like this:
$val = 1;
$arr = Array();
$arr['val'] =& $val;
$arr['val'] = clone $arr['val'];
// Or better yet:
$arr = clone $arr;
$val = 2;
echo $arr['val'];
And this should print out 1 (because the array was cloned, before the referenced variable changed).
Howerver, clone does not work with arrays, it only works with objects.
Any ideas? I really have no clue how to do this. I tried writing a recursive copy function, but that didn't work.
You could unset the index and then reassign by-value instead of by reference.
unset($arr['val']);
$arr['val'] = $val;
Related
Even if it's documented, I need help to better understand this code (only references). I already checked tutorials, but they didn't help me.
// initialize variables
$val = 'it works !';
$arr = [];
// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];
// Get a reference to where we start
$curr = &$arr;
// Loops over keys
foreach($keys as $key) {
// get the reference for this key
$curr = &$curr[$key];
}
// Assign the value to our last reference
$curr = $val;
// visualize the output, so we know its right
var_dump($arr);
echo "<hr><pre>\$arr : "; print_r($arr);
(Source : https://stackoverflow.com/a/31103901/4741362 #Derokorian)
I'll try to explain it for you to understand it a little better, see the working code here. I hope it helps you understand this $curr = &$curr[$key]; line. $curr points to the empty $arr before the foreach starts, In foreach it saves the value of $key into the $arr by reference which was pointed by $curr and then reassigns the reference of the newly saved $key in $arr to the $curr pointer again.
// initialize variables
$val = 'it works !';
$arr = [];
// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];
// Get a reference to where we start
echo "create a space where to save the first key \r\n";
$curr = &$arr;
// Loops over keys
$i = 1;
foreach($keys as $key) {
echo "**************** Iteration no $i ******************\r\n";
// echo "save the value \"$key\" to the reference created earlier in the \$curr variable for the empty array above where the kesy are actually being saved \r\n";
// get the reference for this key
echo "Now save the value of \$key to the array reference present in \$curr and then assigne the reference of newly saved array item to \$curr again \r\n";
$curr = &$curr[$key];
print_r($arr);
$i++;
echo "\r\n\r\n";
}
// Assign the value to our last reference
$curr = $val;
// visualize the output, so we know its right
print_r($arr);
I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)
Here is an example of what I am trying to accomplish:
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
echo $array['aaa']$subarray; // these 2 echos should be the same
echo $array['aaa']['bbb']['ccc']; // these 2 echos should be the same
It should display the same as $array['aaa']['bbb']['ccc'] i.e., "value".
This doesnt work, of course. But is there some simple solution to this?
There could be some function and the $subarrayvalue may be used as a parametr and/or as an array itself like: $subarray = array('bbb','ccc'); I dont mind as long as it worsk.
You could try something like below.
$subarray = "['bbb']['ccc']";
$temp = parse_str("\$array['aaa']".$subarray);
echo $temp;
OR To ignore single quotes -
$subarray = "[\'bbb\'][\'ccc\']";
$temp = parse_str("\$array[\'aaa\']".$subarray);
echo $temp;
Also you may refer - http://php.net/manual/en/function.parse-str.php
Just try using array chunk function http://php.net/manual/en/function.array-chunk.php
here is what actually works!!
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
$string = 'echo $array[\'aaa\']' . $subarray . ';';
eval($string);
Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);
$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1:
$arr[1]=2;
$arr[] = $new_item;
In the above case,it's 2
end() do the job , to return the value ,
if its help to you ,
you can use key() after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array)) should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item) will return all the keys associated with value $new_item, as an array.
Of all these keys we are interested in the one that got added last and will have the max value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n] where $n > count($arr). Stick to using array_* functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr). That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1] to be correct (if it's not, you have a logic error).