How to get variable variable with array value - php

How I can use variable variables with array to get result like is below?
I've tried so far:
// $g_module_id_bar_1['id'] = 5;
$i = 1;
$variablename = 'g_module_id_bar_'.$i;
$key = '\'id\'';
echo $$variablename[$key];
Result should be: 5

You almost had it.
Change $key = '\'id\''; too $key='id';
The reason is because PHP understands that $key contains a string. When accessing an array noramlly, you wouldn't do something like:
<?php
$var = array("hello"=>"world");
echo $var["'hello'"];
which is effectively what you were doing
See for full solution:
https://3v4l.org/qk5ZL

You are trying to escape single quotes but this is useless, just use the string key:
$key = 'id';
echo $$variablename[$key]; // 5

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

How to replace part of a multi array variable with a different variable?

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);

PHP count session variables starting with FAVORITE-LISTING-

With PHP I want to count the session variables $_SESSION key that start with a particular string.
eg:
FAVORITE-LISTING-04
FAVORITE-LISTING-24
FAVORITE-LISTING-58
with the above keys, count for "FAVORITE-LISTING-" will return: 3
Cheers
This should work for you:
<?php
session_start();
$_SESSION['FAVORITE-LISTING-04'] = "foo";
$_SESSION['FAVORITE-LISTING-24'] = "foo";
$_SESSION['FAVORITE-LISTING-58'] = "foo";
$count = substr_count(implode(array_keys($_SESSION)), "FAVORITE-LISTING-");
echo $count;
?>
Output:
3
You can make this working using a variable-variable which PHP does support. But I suggest instead to use a double array:
$_SESSION['FAVORITE-LISTING']['4'] = 'something';
$_SESSION['FAVORITE-LISTING']['24'] = 'something';
$_SESSION['FAVORITE-LISTING']['58'] = 'something';
count($_SESSION['FAVORITE-LISTING']);
That way you can retrieve data much easier and things keep organized.
Since $_SESSION is an array, just loop through it and look at the key's. Anytime a key begins with whatever you're string is you just add one more to the count. Since you're look for the beginning of the string, you want strpos() to equal 0 so you need to use === instead of ==.
$find = 'FAVORITE-LISTING-';
$count = 0;
foreach($_SESSION as $key => $value) {
if(strpos($key, $find) === 0) {
$count++;
}
}

How do I repeat my code 12 times with a loop?

$date_show1 = "01-".$date2;
$date = date($date)."-01";
$date_char = date($date);
$eee2 = mysqli_query($database->connection,"SELECT * FROM bon_info
WHERE date_day = '$date' AND creditcart != '8' AND creditcart != '6' AND
kassa_id = '$kassa_id'") or die(mysqli_error());
$num1 = mysqli_num_rows($eee2);
I tried the following script with a while loop but how can i also change the names of the variables also like
$date_show1 ..2 ..3 ..4 ..5 ..6 ..7 ..8 ..9 ..10 ..11 ..12
$num1 $num2 $num3......
I have no clue what you ask, apart from the numerating variables. You can use an array for that:
$variable[0] = 123;
$variable[1] = 123;
$variable[2] = 123;
$variable[3] = 123;
for($i=0;$i<=3; $i++){
echo $variable[$i];
}
Better usage for this would be a foreach. Imagine you unset value 2, the $i will echo a blank echo, because it doesn't exist. Waste over effort, therefor:
foreach($variable as $key=>$value){
echo $key.' = '.$value;
}
That method also supports non-digit keys (like ['name'] and ['id'])
You can concat a variable to make a variable name like that:
<?php
$my_date_var = "date_show1";
$my_date_var++; // date_show2
echo $$my_date_var; // if defined will echo variable $date_show2

Convert string to variable in PHP?

How do I go about setting a string as a literal variable in PHP? Basically I have an array like
$data['setting'] = "thevalue";
and I want to convert that 'setting' to $setting so that $setting becomes "thevalue".
Thanks for any help!
See PHP variable variables.
Your question isn't completely clear but maybe you want something like this:
//Takes an associative array and creates variables named after
//its keys
foreach ($data as $key => $value) {
$$key = $value;
}
extract() will take the keys of an array and turn them into variables with the corresponding value in the array.
${'setting'} = "thevalue";
It may be evil, but there is always eval.
$str = "setting";
$val = "thevalue";
eval("$" . $str . " = '" . $val . "'");

Categories