Join string and variable to get another variable in PHP - php

Sorry if this has already been asked, but it's hard to search for it... I tried googlin this topic without success.
What I want to do is this:
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo $chosenTheme [0];
I want to join the $layoutColor variable with the word "colors" in order to get the variable $colors2.
How do I do that?
Thanks.

You're best off approaching this by just combining all your options into a single multi-dimensional array:
$layoutColor = 2;
$colors = array();
$colors[1] = array ("F57171", "FACCCC");
$colors[2] = array ("FF9900", "FFC66F");
$chosenTheme = $colors[$layoutColor];
echo $chosenTheme [0];

Try this:
<?php
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo ${$chosenTheme}[0];
Prints:
FF9900

I think you can simplify this using multi dimensional arrays:
$colors = array(
array ("F57171", "FACCCC"),
array ("FF9900", "FFC66F")
);
So...
echo $colors[0];
Or you can user variable variables:
$chosenTheme = ${"colors".$layoutColor};

You may try this
$layoutColor = 2;
$$colors2 = "colors".$layoutColor;
So you'll get $colors2 variable
print_r($colors2); // Array ( [0] => FF9900 [1] => FFC66F )
Notice the double $, that will keep the variable name in the variable.

Try with:
$layoutColor = 2;
$string = "color";
echo $$string.$layoutColor;

You need to use dynamic variables
$$chosenTheme = "colors".$layoutColor;
then access the array by using this variable
$chosenTheme

This might not be an answer to your question but, depending on your specific context, try something like this:
$layoutColor = 2;
$colors = array (
Array("F57171", "FACCCC"),
Array ("FF9900", "FFC66F")
);
echo $colors[$layoutColor][0];
A multi dimensional array is a lot easier to read

Related

Php use a string as variable name print_r

my scenario is as follow i have lets say 2 arrays $array_0 and $array_1 then i want to print it in a while better in a for
for ($i=0;$i<=1;$i++){
print_r(array($array?));
}
how i should declare de array to print_r i try set the string of the name in a variable before but maybe its lacks something
for ($i=0;$i<=1;$i++){
$str_array='$array_'.$i;
print_r(array($str_array));
}
but that prints something like
Array
(
[0] => $array_0
)
Array
(
[0] => $array_1
)
Sounds like you're looking for variable variables.
$array_0 = ['foo'];
$array_1 = ['bar'];
for ($i = 0; $i <= 1; $i++) {
print_r(${'array_' . $i}); // Here we "build" the variable name
}
Here's a demo: https://3v4l.org/PLApU
You can read more about variable variables in the manual: https://www.php.net/manual/en/language.variables.variable.php
You need to use "variable variable" by putting a second dollar sign. Here is an example:
$arr_1 = array(1=>'a', 2=>'b');
$arr_2 = array(1=>'c', 2=>'d', 3=>'e');
for($i=1; $i<=2; $i++){
$arrname = 'arr_'.$i;
print_r(${$arrname});
}
You can use $$arrname instead of ${$arrname}; however I found the latter more clear to understand what's happening.

add values of array in php

Hi i know its very simple but im stuck in this.
Im fetching data by using join from database.. Now i got the values in array. i want to add these two value in a variable.
Code is below..
$sql = "SELECT event_details.max_team_size FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryAll();
$array has got the values like this..
Array
(
[0] => Array
(
[max_team_size] => 6
)
[1] => Array
(
[max_team_size] => 8
)
)
I want to add these two max_team_size into a single variable and use that later to compare.
$sum = 0;
foreach($array as $data){
$sum += $data->max_team_size;
}
echo $sum;
Sum you can get from SQL also by using SUM function
SELECT SUM(event_details.max_team_size) FROM booking_details...
In Yii the solution will be
$sql = "SELECT SUM(event_details.max_team_size) as total FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryRow();
In PHP to sum particular key in single array you can convert it to single array by using array_column function and then use sum function
$array = array_column($array, 'max_team_size');
$total = array_sum($array);
Note: array_column will work PHP >= 5.5, for PHP < 5.5 you can use foreach loop
Define an empty array like this:
$maxArr = array();
You can run a foreach loop for your array now and add variable.
Like this:
foreach($gotArr as $key=>$val){
}

storing multiple values in same array with same index

If I want to add multiple values in array having same index in PHP, then can it be possible to create this type of an array? For e.g.,
fruits[a]="apple";
fruits[a]="banana";
fruits[a]="cherry";
fruits[b]="pineapple";
fruits[b]="grappes";
I want array to look like as below:-
fruits = {[a]=>"apple",[a]=>"banana",[a]=>"cherry",[b]=>"pineapple",[b]=>"grappes"};
You cannot define multiple value under same key or index.
In your case -
fruits[a]="apple";
fruits[a]="banana";
Here apple will be replaced by banana.
Instead, you may define array as -
fruits[a][] = "apple";
fruits[a][] = "banana";
Edit: i updated my answer with php code, but i don't code php usually, this might not be the most optimal solution, i tried this code in a php sandbox
$subarray1[0] = "apple";
$subarray1[1] = "banana";
$subarray1[2] = "cherry";
$subarray2[0] = "pineapple";
$subarray2[1] = "grappes";
$fruits[0] = $subarray1;
$fruits[1] = $subarray2;
foreach( $fruits as $key => $value ){
foreach( $value as $key2 => $value2 ){
echo $key2."\t=>\t".$value2."\n";
}
}
use implode and explode .
subarray1[0] = "apple"
subarray1[1] = "banana"
subarray1[2] = "cherry"
subarray2[0] = "pineapple"
subarray2[1] = "grappes"
It is store data with ,(comma)
$ar="";
for($i=0;$i<=count(subarray1);$i++)
{
$ar[]=subarray1[$i];
}
$rt=implode(',',$ar);
echo $rt;
It is Remove ,(comma) form array
$ex=explode(",",$ar);
print_r($ex);

Add extra number in ordered array

Which is the best way to insert a new number in an already ascendant ordered array?
$new_number = 6;
$old_array = array(1,3,4,5,7,8,10);
// $new_array must be 1,3,4,5,6,7,8,10
Why not just add it and sort it again ?
$new_number = 6;
$old_array = array(1,3,4,5,7,8,10);
array_push($old_array,$new_number);
sort($old_array);
Simple:
$old_array = array(1,3,4,5,7,8,10);
$old_array[] = 6;
sort($old_array);
/* Notes:
sort() will actually change the array which you pass to it
don't do: $old_array = sort($old_array);
*/

PHP in_array isn't finding a value that is there

I have an array called $friend_array. When I print_r($friend_array) it looks like this:
Array ( [0] => 3,2,5 )
I also have a variable called $uid that is being pulled from the url.
On the page I'm testing, $uid has a value of 3 so it is in the array.
However, the following is saying that it isn't there:
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.
What am I doing wrong? Any help would be greatly appreciated!
Output of
Array ( [0] => 3,2,5 )
... would be produced if the array was created by something like this:
$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);
Based on your question, I don't think this is what you meant to do.
If you want to add three values into the first three indexes of the array, do the following:
$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');
or, as a shorthand for array_push():
$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';
Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:
// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
}
Working example
Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.
Example:
$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;
Your above if statement will then work correctly.

Categories