I am trying to dynamically generate a string n then use it inside list() to catch array values in variables.
Code :
<?php
$bubba = "value1, value2, value3, value4, value5, value6, value7";
$hubba = explode(",", $bubba);
$num = count($hubba);
ob_start();
for($i=1; $i<=$num; $i++){
echo ('$k'.$i.', ');
}
$varname = ob_get_clean();
$varname = substr($varname, 0, -2);
list(echo $varname;) = $hubba;
I want this to look like:
list($k1, $k2, $k3, $k4, $k5, $k6, $k7) = $hubba;
echo $k1; // must echo value1
?>
But, list simply is not-ready to accept the variable string. How to do this ?
You are trying to solve a problem the wrong way. Most experienced developers will tell you that they have been down this road and it's a dead end. Why use $k0 instead of the existing $k[0]? However, for fun, here is a working example:
extract($hubba, EXTR_PREFIX_ALL, 'k');
echo $k_0;
Or another, for fun, that does it the way you describe:
foreach($hubba as $k => $v) {
${'k'.($k+1)} = $v;
}
echo $k1;
Or finally, for more fun, using list() for no apparent reason:
for($i=1; $i<=$num; $i++) {
$var[] = '$k'.$i;
}
$vars = implode(', ', $var);
eval("list($vars) = \$hubba;");
echo $k1;
I would encourage you to include WHY you think you need this and there is definitely a better solution.
Related
I have a string in a table field that looks like this:
part1=1,part2=S,part3=Y,part4=200000
To call it from the table I do this:
while($row = mysqli_fetch_array($result)) {
$row['mystring'];
}
My problem is that I need to separate the parts into variables for example:
From this:
part1=1,part2=S,part3=Y,someothername=200000
To This:
$part1 = '1';
$part2 = 'S';
$part3 = 'Y';
$someothername = '200000';
How can I do this?
Use like this
parse_str( str_replace(",", "&", "part1=1,part2=S,part3=Y,someothername=200000") );
Use with there name like:
$part1 // return 1
$part2 // return S
$part3 // return Y
works like you want, see the demo
First split string:
$s = "part1=1,part2=S,part3=Y,part4=200000";
$a = explode(",",$s);
then foreach part of string ("part1=1"...) create an array and explode as variable:
foreach($a as $k=>$v)
{
$tmp = explode("=",$v);
$tmp = array($tmp[0]=>$tmp[1]);
extract($tmp);
}
echo $part1;
If you use PHP 5.3+ you can use array_map
<?php
$string = 'part1=1,part2=S,part3=Y,part4=200000';
array_map(function($a){
$tmp = explode('=', $a, 2);
global ${$tmp[0]}; //make vars available outside of this function scope
${$tmp[0]} = $tmp[1];
}, explode(',', $string));
//Variables available outside of array_map scope
echo $part1 . '<br>';
echo $part2 . '<br>';
echo $part3 . '<br>';
echo $part4 . '<br>';
?>
Double explode your string to get the wanted field :
$string ="part1=1,part2=S,part3=Y,someothername=200000";
foreach (explode(',', $string) as $parts) {
$part = explode('=', $parts);
$array[$part[0]] = $part[1];
}
var_dump($array);
Output :
array(4) {
["part1"]=>
string(1) "1"
["part2"]=>
string(1) "S"
["part3"]=>
string(1) "Y"
["someothername"]=>
string(6) "200000"
}
I wouldn't suggest the use of variable variables to get the output as :
$part1 = ...
$part2 = ...
Using an array is probably the easier and safest way to do here. As suggested in my comment, it avoid potential conflicts with variable names.
You can use something called 'Variable variables'. You can declare the content of a variable as a variable, if you use double dollar sign, instead of a single one. For example:
$fruit = "apple";
$$fruit = "this is the apple variable";
echo $apple;
It would output the following:
this is the apple variable
You have to be a bit more tricky with defining variables from an array, as you'd have to enclode the original variable in curly brackets. (for example: ${$fruit[0]})
So the answer to your question is:
$parts = "part1=1,part2=S,part3=Y,someothername=200000";
$parts_array = explode(",", $parts);
foreach ($parts_array as $value) {
$temp = explode("=", $value);
${$temp[0]} = $temp[1];
}
echo "$part1, $part2, $part3, $someothername";
PHPFiddle link: http://phpfiddle.org/main/code/adyb-ug5n
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c;$i++){
$v = '$var'.$i;
$splited = list($v) = $my_array;
}
?>
input:
$my_array
But expected output:
if I echo $var0, $var1, $var2;
hello, world, howareu
How to create dynamic PHP variables based upon the array count and then convert them into a list as a string?
You do not need list for that. $$ will suit you perfectly.
$my_array = array("hello", "world", "howareu");
foreach ($my_array as $key => $val)
{
$a = 'var'.$key;
$$a = $val;
}
echo $var0,", ", $var1,", " $var2;
Take a look here - Variable variables
Added:
or if you need count and for
for ($i = 0; $i < count($my_array); $i++)
{
$a = 'var'.$i;
$$a = $my_array[$i];
}
echo $var0,", ", $var1,", " $var2;
Of course, this line echo $var0,", ", $var1,", " $var2; sucks and looks like crap :) But in order to receive EXACTLY what you want, you need to modify variables, output like I've wrote, or use some function like implode with grue ', '.
Updated:
But if you need just that output, why not to use simple implode(', ', $my_array) :)
it's a matter of the data you need to process...if it's pretty static, you don't need the second foreach() for example, since you compare the keys anyways...
foreach($datavalueas $resultdatakey=>$resultdatavalue){
if($resultdatakey== 'A'){
//stuff for a
}
if($resultdatakey== 'B'){
//stuff for b
}
}
would become
if(isset($datavalueas['A'])){
//stuff for a
}
if(isset($datavalueas['B'])){
//stuff for b
}
since the foreach uses copies of the array, which are pretty bad for the performance...
Assuming i got your question right, you could use something like:
$array = array( 'x', 'y', 'z' );
foreach ($array as $name )
$$name = rand(1,100);
var_dump($x);
the $$ is key here, the first $ implies the variable as the second $ is used as the identifier for the variable. In this case the value being iterated over in the array. Giving us 3 variables: $x, $y, $z.
-- edit:
the correct code, besides using extract():
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i < $c;$i++){
$v = 'var'.$i;
$$v = $my_array[$i];
}
echo "$var0, $var1, $var2";
?>
You can create dynamic variables via variables variable as Mr.kovpack have stated here. In below code you can access the variables from 0 to $c-1(count of array) as per your comment to Mr.kovpack.
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
${'var'.$i} = $my_array[$i]; //Dynamic variable creation
// $splited = list($v) = $my_array;
}
echo $var0.$var1.$var2;
or you could use like below:
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
$a='var'.$i;
$$a = $my_array[$i];
}
echo $var0."-".$var1."-".$var2;
You can read more on it here
I need to convert all items in array to variables like:
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
And I want to convert it to this:
$apple = 5;
$banana = 7;
$orange = 8;
Like normal variables. Is it possible?
Seems like a silly thing to do, why not convert it into an associative array? But if you must:
foreach($item as $x) {
list($name, $val) = explode('=', $x, 2);
$$name = $val;
}
You can try to join the array and parse the string into variables
parse_str(implode('&',$item));
You can do it like this
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
foreach($item as $row)
{
$new = explode('=',$row);
$array[$new[0]] = $new[1];
}
extract($array);
echo $apple;
echo $banana;
echo $orange;
Your array looks like someone exploded an ini file on its newlines.
Implode with newlines, then parse, then call extract() to generate the variables. (Demo)
extract(
parse_ini_string(
implode(PHP_EOL, $item)
)
);
echo "$apple $banana $orange";
Using explode() or parse_ini_string() or preg_ functions (etc.) will render the numeric values as string-type.
If you'd like the numeric values to be integer-typed, then using %d in the "format" parameter of sscanf() will be most direct. (Demo1)
foreach ($item as $string) {
[$key, $$key] = sscanf($string, '%[^=]=%d');
}
Generally speaking, I do not advise the generation of individual variable (I more strenuously advise against variable variables). Perhaps an associative array would be suitable. (Demo)
$result = [];
foreach ($item as $string) {
[$key, $result[$key]] = sscanf($string, '%[^=]=%d');
}
var_dump($result);
I have a variable, let's call it $var that echoes out something like:
32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45
The variable is created from a combination of a form submission and jQuery Sortables (which is why everything ends up in one variable, not two). The order is very important.
What I'd like to end up with is two variables (can be arrays) that would be:
$newVar1 = 32,18,24,45,24
$newVar2 = Widgets: 18,Widgets: 24,Widgets: 45,Widgets: 24,Widgets: 45
I started by:
$newVars = explode(",",$var);
But I'm at a loss of where to go from there. I've tried a variety of statements such as:
foreach ($newVars as $newVar) :
//Various explode() functions tried here.
endforeach;
If anybody has any idea what I'm missing I would certainly appreciate the help.
Thank you,
Eric
It's not very pretty, but it'll do the trick.
<?php
$str = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$entries = explode(",", $str);
$parts1 = array();
$parts2 = array();
foreach ($entries as $e)
{
$temp = explode("-", $e);
$parts1[] = $temp[0];
$parts2[] = $temp[1];
}
print_r($parts1);
print_r($parts2);
?>
Running example: http://ideone.com/KkL06f
Have you tried something like this:
public function just_a_test() {
$var = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$vars = explode(',', $var);
$partsA = $partsB = array();
foreach ($vars as $aVar) {
preg_match('/^(\d+)-(Widgets: \d+)$/i', $aVar, $parts);
$partsA []= $parts[0];
$partsB []= $parts[1];
}
echo '<pre>';
print_r($partsA);
print_r($partsB);
echo '</pre>';
}
You could easily end up with output like yours by calling the implode() with each array.
This is probably a simple question, but how do you iterate through an array, doing something to each one, until the last one and do something different?
I have an array of names. I want to output the list of names separated by commas.
Joe, Bob, Foobar
I don't want a comma at the end of the last name in the array, nor if there is only one value in the array (or none!).
Update: I can't use implode() because I have an array of User model objects where I get the name from each object.
$users = array();
$users[] = new User();
foreach ($users as $user) {
echo $user->name;
echo ', ';
}
How can I achieve this and still use these objects?
Update: I was worrying too much about how many lines of code I was putting in my view script, so I decided to create a view helper instead. Here's what I ended up with:
$array = array();
foreach($users as $user) {
$array[] = $user->name;
}
$names = implode(', ', $array);
Use implode:
$names = array('Joe', 'Bob', 'Foobar');
echo implode(', ', $names); # prints: Joe, Bob, Foobar
To clarify, if there is only one object in the array, the ', ' separator will not be used at all, and a string containing the single item would be returned.
EDIT: If you have an array of objects, and you wanted to do it in a way other than a for loop with tests, you could do this:
function get_name($u){ return $u->name; };
echo implode(', ', array_map('get_name', $users) ); # prints: Joe, Bob, Foobar
$array = array('joe', 'bob', 'Foobar');
$comma_separated = join(",", $array);
output: joe,bob,Foobar
Sometimes you might not want to use implode.
The trick then is to use an auxiliary variable to monitor not the last, but the first time through the loop.
vis:
$names = array('Joe', 'Bob', 'Foobar');
$first = true;
$result = '';
foreach ($names as $name)
{
if (!$first)
$result .= ', ';
else
$first = false;
$result .= $name;
}
implode(', ', $array_of_names)
psuedocode....
integer sigh=container.getsize();
sigh--;
integer gosh=0;
foreach element in container
{
if(gosh!=sigh)
dosomething();
else
doLastElementStuff();
gosh++;
}
looking at all the other answers, it seems PHP has gotten a lot more syntactic S since I last wrote anything in it :D
I come accross this a lot building SQL statements etc.
$joiner = " ";
foreach ($things as $thing) {
echo " $joiner $thing \n";
$joiner = ',';
}
FOr some reason its easier to work out the logic if you think of the ",", "AND" or "OR" as an option/attribute that goes before an item. The problem then becomes how to suppress the the "," on the first line.
I personally found the fastest way (if you're into micro optimization) is:
if(isset($names[1])) {
foreach ($names as $name) {
$result .= $name . ', ';
}
$result = substr($result, 0, -2);
} else {
$result = $names[0];
}
isset($names[1]) is the fastest (albeit not so clear) way of checking the length of an array (or string). In this case, checking for at least two elements is performed.
I actually find it easier to create my comma delimited text a little differently. It's a bit more wordy, but it's less function calls.
<?php
$nameText = '';
for ($i = 0; $i < count($nameArray); $i++) {
if ($i === 0) {
$nameText = $nameArray[$i];
} else {
$nameText .= ',' . $nameArray[$i];
}
}
It adds the comma as a prefix to every name except where it's the first element if the array. I have grown fond of using for as opposed to foreach since I have easy access to the current index and therefore adjacent elements of an array. You could use foreach like so:
<?php
$nameText = '';
$nameCounter = 0;
foreach ($nameArray as $thisName) {
if ($nameCounter === 0) {
$nameText = $thisName;
$nameCounter++;
} else {
$nameText .= ',' . $thisName;
}
}