What I am doing that I want to generate a list based on how many items are in an array, so I have counted the items and loop over them, create a number based var and construct a string $var which contains $a1,$a2.... and assigns the $var to list list($var)
and tried to access $a1 but it gives me the error "Undefined variable: a1"
Is there any other way to do it?
Here is my code:
$arr = array('1','2','3');
$listsize = count($arr);
$var='';
for($i=1;$i<=$listsize;$i++){
$var.='$a'.$i;
if($i!=$listsize){
$var.=',';
}
}
list($var) = $arr;
echo $a1;
What you are looking for is variable variables.
In PHP, you can dynamically assign variables names (not just values).
Here is an example:
$foo = "Hello" . 1;
# In this line, I am taking the value of the variable $foo (Hello1) and
# using that as as a variable name. This is equivalent to
# $Hello1 = "World", except the variable is dynamic (hence variable variables).
$$foo = "World";
print $Hello1; # This will print World
Why not use extract()?
Try this:
$values = array('1','2','3');
$variables = array();
$length = count($values);
$key = 'a1';
for ($i = 0; $i < $length; $i++){
$variables[$key] = $values[$i];
$key++;
}
extract($variables);
echo $a1, $a2, $a3;
You can solve your problem without loops. Array $as is filled with your data, that has keys a1 to aX:
$arr = array('1', '2', '3', 'test', true, 4.56);
$keys = array_map(function($n) { return "a$n"; }, range(1, count($arr)) );
$a = array_combine($keys, $arr);
Array $as has keys and values like output bellow:
Array
(
[a1] => 1
[a2] => 2
[a3] => 3
[a4] => test
[a5] => 1
[a6] => 4.56
)
I advice you to use access to variables via array like $a['a3'], and not via variables like $a3.
If you would like to have $a1 ... $aX variables, extract array like:
extract($a);
Related
$str='abcde';//for sub-question numbers
for ($i=1; $i <=10 ; $i++) {//i loop is for question numbers 1 to 10
for ($j=0; $j<5 ; $j++) {//j loop is for sub-questions from a to e
$q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
}
}
Here the main idea is to create 50 variables from q1a,q1b,... till q10d,q10e.
I'm not 100% clear on what the values of those variables will be, but here is how to create an array with those variable names in them.
$questions = array(1,2,3,4,5,6,7,8,9,10); //questions
$subQuestions = array('a','b','c','d','e'); //sub-question
$allQuestions = array();
foreach($questions as $question) {//loop the questions
foreach($subQuestions as $subQ) {//loop the sub questions
// I'm not clear what you're trying to do here -> $q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
$allQuestions["q" . $question . $subQ] = "I'm an empty value right now"; //what value goes here?
}
}
var_dump($allQuestions);
You can do something like this
$values = array("q1a", "q1b", "q1c", "q1d", "q1e", "q2a", "q2b", "q2c", "q2d", "q2e");
for($i=;$i<$sizeof($values);$i++)
{
$values[$i] = $_POST['q{$i}{$str[j]}'];
}
If all your POST vars which you want to grab are prepended with q then just filter them with array_filter().
Then you can use extract(), but tbh, you should just use the array.
<?php
$_POST = [
'q1' => 'baz',
'foo' => 'bar',
];
$q = array_filter($_POST, function($k) {
return substr($k, 0, 1) === 'q';
}, ARRAY_FILTER_USE_KEY);
extract($q);
// filtered array
print_r($q);
// extract'ed
echo $q1;
Result:
Array
(
[q1] => baz
)
baz
https://3v4l.org/rvMR6
I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the second smallest value?
Thanks.
Use compact to set the variables to one array, sort the array, then use array slice to get the second value.
Then optionally echo the key of the second value.
$a = 2;
$b = 7;
$c = 6;
$d = 1;
$arr = compact('a', 'b', 'c', 'd');
asort($arr);
$second = array_slice($arr,1,1);
Echo "variable name " . Key($second) ."\n";
Echo "value " . ${key($second)};
https://3v4l.org/SVdCq
Updated the code with how to access the original variable from the array
Unless you have a structured way of naming your variables eg prefix_x there is no real way.
Recommended way is using an array like this:
$array = array(
"a" => 3,
"b" => 2,
"c" => 1,
"d" => 6
);
// Sort the array descending but keep the keys.
// http://php.net/manual/en/function.asort.php.
asort($array);
// Fetch the keys and get the second item (index 1).
// This is the key you are looking for per your question.
$second_key = array_keys($array)[1];
// Dumping the result to show it's the second lowest value.
var_dump($array[$second_key]); // int(2).
To be more in line with your question you can create your array like this.
$array = array();
$array['variable_one'] = $variable_one;
$array['some_random_var'] = $some_random_var;
$array['foo'] = $foo;
$array['bar']= $bar;
// Same code as above here.
Instead of using 4 variables for 4 integer values, you can use an array to store these values. Sort the array and print the second index of the array i.e. 1.
<?php
$x = array(2,3,1,6);
$i = 0, $j = 0, $temp = 0;
for($i = 0; $i < 4; $i++){
for($j=0; $j < 4 - $i; j++){
if($x[$j] > $x[$j+1]){
$temp = $x[$j];
$x[$j] = $x[$j+1];
$x[$j+1] = $temp;
}
}
}
for($j = 0; $j < 4; $j++){
echo $x[$j];
}
echo $x[1];
?>
First you need to have all Variables in an Array. You can do this this way:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
or this way:
$array['a'] = 3;
$array['b'] = 6;
// etc
Then you need to sort the Items with natsort() to receive a natural Sorting.
natsort($array);
Then you flip the Array-Keys with the Values (In Case you want the Value, skip this Line)
$array = array_flip($array);
After this you jump to the next Item in the Array (Position 1) by using next();
echo next($array);
Makes in Total a pretty short Script:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
natsort($array);
$array = array_flip($array);
echo next($array);
I have two arrays:
array(1,2,3,4,5)
array(10,9,8,7,6)
Final array Needed:
array(0=>1:10,1=>2:9,2=>3:8,3=>4:7,4=>5:6)
I can write a custom function which would be quieck enough!! But i wanted to use a existing one so Is there already any function that does this in php? Pass the two input arrays and get the final array result? I read through the array functions but couldn't find any or combination of function that would provide me the result
No built in function but really there is nothing wrong with loop .. Just keep it simple
$c = array();
for($i = 0; $i < count($a); $i ++) {
$c[] = sprintf("%d:%d", $a[$i], $b[$i]);
}
or use array_map
$c = array_map(function ($a,$b) {
return sprintf("%d:%d", $a,$b);
}, $a, $b);
Live Demo
Try this :
$arr1 = array(1,2,3,4,5);
$arr2 = array(10,9,8,7,6);
$res = array_map(null,$arr1,$arr2);
$result = array_map('implode', array_fill(0, count($res), ':'), $res);
echo "<pre>";
print_r($result);
output:
Array
(
[0] => 1:10
[1] => 2:9
[2] => 3:8
[3] => 4:7
[4] => 5:6
)
See: http://php.net/functions
And especially: http://nl3.php.net/manual/en/function.array-combine.php
Also, I don't quite understand the final array result?
Do you mean this:
array (1 = 10, 2 = 9, 3 = 8, 4 = 7, 5 = 6)
Because in that case you'll have to write a custom function which loops through the both arrays and combine item[x] from array 1 with item[x] from array 2.
<?php
$arr1=array(1,2,3,4,5);
$arr2=array(10,9,8,7,6);
for($i=0;$i<count($arr1);$i++){
$newarr[]=$arr1[$i].":".$arr2[$i];
}
print_r($newarr);
?>
Use array_combine
array_combine($array1, $array2)
http://www.php.net/manual/en/function.array-combine.php
This question already has answers here:
PHP - Variable inside variable?
(6 answers)
Closed 8 years ago.
I want to access a variable that is either called $item1, $item2 or $item3.
I want to access this variable inside a for loop where $i is ++ every time. using $item.$i or something similar. However using that code means that I am trying to join the contents of two variables, and there is no variable called $item.
Arrays: A Better Method
While PHP does permit you to build dynamic variable names from various other values, you probably shouldn't in this case. It seems to me that an array would be more appropriate for you:
$items = array( 0, 12, 34 );
You could then access each value individually:
echo $items[0]; // 0
echo $items[1]; // 12
Or loop over the entire set:
foreach ( $items as $number ) {
echo $number; // 1st: 0, 2nd: 12, 3rd: 34
}
Merging Multiple Arrays
You indicated in the comments on the OP that $item1 through $item3 are already arrays. You could merge them all together into one array if you like with array_merge(), demonstrated below:
$item1 = array( 1, 2 );
$item2 = array( 3, 4 );
$item3 = array( 5, 6 );
$newAr = array_merge( $item1, $item2, $item3 );
print_r( $newAr );
Which outputs:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
If You Must: Dynamic Variable Names
For completeness, if you were to solve your problem by dynamically constructing variable names, you could do the following:
$item1 = 12;
$item2 = 23;
$item3 = 42;
for ( $i = 1; $i <= 3; $i++ ) {
echo ${"item".$i} . PHP_EOL;
}
build the variable name you want to access into another variable then use the variable variable syntax
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for ($i = 1; $i<=3; $i++) {
$varname = 'item' . $i;
echo $$varname;
}
?>
output:
abc
Note there are other ways to do this, see the manual.
Use ${'item'.$i}
If $i == 1, then you will access $item1.
But it's better to use arrays in your case.
for ($i =1;$i<4;$i++){
$var = 'item'.$i;
echo $$var;
}
Here you are using the the double $ to create a variable variable.
Can you use an array instead of individual variables? then you can reference array elements by index value based in i.
$items = array();
$i = 1;
$items[$i] = "foo";
$i++;
$items[$i] = "bah";
echo $items[1], $items[2]; // gives "foobah"
It's a little late, and the accepted answer is the proper way to do this, but PHP does allow you to access variable variable names in the way OP describes:
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for($i=1;$i<=3;$i++)
echo ${"item$i"}; //Outputs: abc
?>
I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;