Use variables in the name of the variable [duplicate] - php

This question already has answers here:
variable variables
(5 answers)
Closed 3 years ago.
I have two arrays:
$my_array1= array("A", "B");
$my_array2= array("1", "2");
Is it possible to use variables ($x) in the index of the array like this:
for ($x = 1; $x <= 2; $x++) {
Echo $my_array.$x[0];
}
How to achieve this?

After referred in comment , i think it's work : here
$my_array1= array("A", "B");
$my_array2= array("1", "2");
and re-use your loop like:
for ($x = 1; $x <= 2; $x++) {
// to init the new name of array
$init = 'my_array'.$x;
// to use variable in the name of variable
Echo $$init[0];
}
I hope it's help you

I think what you're looking for is to be able to use key / value pairs.
You can do something like:
$array = array(
1 => "a",
2 => "b",
3 => "c",
4 => "d",
);
foreach ($array as $key => $value) {
echo "{$key} => {$value} ";
}
Or loop througout the numeric key values as you like.

Related

Why does For work, but ForEach does not in PHP? [duplicate]

This question already has answers here:
Why can't I update data in an array with foreach loop? [duplicate]
(3 answers)
Closed 1 year ago.
We have an array of strings of numbers
$a = ["1", "2", "3"];
foreach loop doesn't change the type, result: [0]=>string(1) "1"
foreach ($a as $v) $v = (int) $v;
for loop makes ints from strings, result: [0]=>int(1)
for ($i = 0; $i < count($a); $i++) $a[$i] = (int) $a[$i];
Please, explain why is that?
The same reason that
$v = $a[0];
$v = int($v);
doesn't change $a. $v is a copy of the array element, not a reference to it.
You can make it work using a reference variable
foreach ($a as &$v) {
$v = (int)$v;
}

Loop through an array (+100 values) [duplicate]

This question already has answers here:
Show the two elements in foreach loop in every iteration? [duplicate]
(4 answers)
Closed 1 year ago.
This is my array:
$my_array = array("1", "2", "3", "4");
I want to achieve something like this:
1 vs 2
3 vs 4
Because the length of my array is only 4 it was easy for me to do this:
echo $my_array[0]." vs ".$my_array[1];
echo "<br>";
echo $my_array[2]." vs ".$my_array[3];
But how can I achieve this if my array has more than 100 values? I also want to account for odd numbers of array elements.
You can use a "for" loop, with an increment of two for every loop :
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
If you're not sure your array always contains an even number of indexes, you can add a condition in order to ignore the last case if there is no more pair to do.
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
if($i !== $len-1) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
}
Sure, for loop is the obvious answer, but there are more interesting ones ;)
$my_array = ["1", "2", "3", "4"];
$new_array = array_map(
function($v) {return isset($v[1]) ? "$v[0] vs $v[1]<br/>" : null; },
array_chunk($my_array, 2)
);
print_r($new_array);
Output:
Array
(
[0] => 1 vs 2<br/>
[1] => 3 vs 4<br/>
)
You can use a for loop to loop through the array.
$my_array = array("1", "2", "3", "4","5","6");
for ($x = 0; $x < sizeof($my_array); $x = $x+2) {
echo $my_array[0+$x]." vs ".$my_array[1+$x];
echo "<br>";
}

Own implementation of array_unique() [duplicate]

This question already has answers here:
fastest way to find if all the elements of an array are distinct?
(4 answers)
Closed 6 years ago.
I have this array:
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
Now I want to get all unique values. Means the result should be:
$result = array("a", "b", "c");
Now I know that this can easily be solved with array_unique(). But I want to write my own little implementation of array_unique() just using a for loop, unset() and array_values().
Something like this maybe? Here we are looping through and array starting in one for from the position 0 and in the other from 1. We compare the $i position with all the others in array and if it finds two same it removes the second one.
<?php
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
$count = count($number);
for($i = 0; $i < $count; $i++) {
for($j = $i+1; $j < $count; $j++) {
if(isset($number[$j]) && isset($number[$i]) && $number[$i] == $number[$j]) {
unset($number[$j]);
}
}
}
print_r($number);
use array_unique()
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=array_unique($number);
print_r($unique_array);
?>
//second posibility
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=[];
foreach($number as $val)
{
$unique_array[$val]=$val;
}
print_r(array_values($unique_array));
?>
//Third posibility with for,unset,array_value
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$count=count($number);
for($i=0;$i<$count;$i++)
{
if($i<count($number))
{
for($j=$i+1;$j<$count;$j++)
{
if($number[$i]==$number[$j])
{
unset($number[$j]);
}
}
}
}
$number=array_values($number);
print_r($number);
?>
expected result is
Array ( [0] => a [1] => b [2] => c )

Sorting integer value in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have 19 variables in a php file.
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
.....
.....
$s = 32;
What i need, I need to show only top 5 value. And there is similar value for some variables. In that case, I need to show the first value only if it is in the top 5 value.
I am not having any clue on doing this.
After receiving some feedback given bellow, i have used array and asort
Here is the example-
<?php
$fruits = array("a" => "32", "b" => "12", "c" => "19", "d" => "18");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The output looks like this:
b = 12 d = 18 c = 19 a = 32
I need the reverse result. Meaning, 32, 19, 18, 12.....
Any help. Just dont know the exact command
This is best done by putting the values of the variables into an array and running
sort($arr); (this is from lowes to highest).
rsort($arr); sorts high to low.
http://php.net/manual/en/array.sorting.php
Then you can get the first values at array-index 0,1,2,3 and 4 which will be the biggest numbers.
So:
$arr= array ($a,$b,$c, ....);
rsort($arr);
var_dump($arr); // gives the output.
$arr[0] // biggest number
$arr[4] // 5th biggest number.
A funny way to do this:
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
$array = compact(range('a', 'h'));
rsort($array);
foreach(array_slice($array, 0, 5) as $top) {
echo $top, "\n";
}
Output
92
51
27
23
20
Demo: http://3v4l.org/Wi8q7
Do they need to be individual variables? Storing the values in an array is a better option. So, either manually put all the variables into an array, or change your structure to something more like:
$arr = array(
'a' = 20,
'b' = 23,
'c' = 2,
'd' = 92,
'e' = 51,
....
....
's' => 32
);
or similar. Then use sort() to sort the array:
sort($arr);
To get the top 5, use array_slice():
$arr = array_slice($arr, 0, 5);
See demo
Note: sort() may not be best option for you depending on the desired result. For other sorting options, consult the manual: http://php.net/manual/en/array.sorting.php
<?php
array_push($data,$a);
array_push($data,$b);
.
.
.
$sorted_array = usort($data, 'mysort');
$top5 = array_splice($sorted_array,5);
if(in_array($your_variable,$top5)){
return $top5[0];
}else {
return $top5;
}
function mysort($a,$b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
?>
$array=array();
for ($i=97;$i<=115;$i++){ //decimal char codes for a-s
$var =chr($i);
$array[]= $$var; //variable variable $a- $s
}
asort($array);
var_dump($array);

How to access php variable using concatenation [duplicate]

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
?>

Categories