<?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
Related
implode(',', $a);
I want to attach the $q variable in front of the $a so like this
implode(',', $q.$a);
But that doesn`t work. How can i put 2 variables in a implode function?
$a is an array with domain names like "com, org" and $q is the text (string) you type in before the domain names will appear.
I get the following error:
invalid argument passed in line..
Whole code:
$a = ['nl','net','com','co'];
$q = $_REQUEST["q"];
$domain = explode(".", $q);
$ext = #$domain[1] ?: ' ';
if (empty($ext)) {
echo implode(',',$a);
} else if (in_array($ext, $a)) {
echo $q;
} else {
$r = [];
foreach ($a as $x) {
if (strstr($x, $ext)) {
$r[] = $x;
}
}
echo (count($r)) ? implode(',',$r) : implode(',',$a);
}
If $a is an array and $q is the prefix string you can achieve that with 2 steps:
Add the prefix with:
$a = array("com", "co");
$q = "robot.";
foreach ($a as &$value)
$value = $q.$value;
Second, use the implode:
echo implode(',',$a);
output is:
robot.com,robot.co
Edited
I think this will be more suitable for you:
$a = array("com", "co", "org");
$q = "robot.c";
$arr = explode(".", $q);
$output = array();
foreach ($a as &$value) {
if (substr($value, 0, strlen($arr[1])) === $arr[1])
$output[]= $arr[0] . "." . $value;
}
echo implode(',',$output);
In this code you take the domain prefix and search for all domain name that may be fit for the prefix.
Notice that is this example we have domain org but he does not show up because your prefix is c
You need to add your $q before implode function. You can add your $q into your $a array using array_map function.
$array = array('com', 'org', 'net');
$q = 'test';
$array = array_map(function($value) {
$q= "test"; // you $q value goes here.
return $q.".".$value;
}, $array);
echo implode(',',$array);
Assuming that your business logic guarantees that $a is never empty, then here is the most direct, efficient, and concise technique...
Code: (Demo)
$a = ['nl', 'net', 'com', 'co'];
$q = 'example';
echo "$q." . implode(",$q.", $a);
Output:
example.nl,example.net,example.com,example.co
See how there is no need to loop or call any additional functions?
This basic technique of expanding the delimiting glue can be seen in other usages like:
echo '<tr><td>' . implode('</td><td>', $array) . '</td></tr>';
The idea is that you prepend what you need before the first value, then you declare the glue to be the characters that you need to occur after each value AND before the next value.
Merge an array with a string variable in PHP with the help of implode function
$a = array("com", "co");
$q = "robot.c";
$temp = explode(".",$q);
foreach ($a as $value)
echo $value = $temp[0].".".$value;
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.
I have unknown number of variables, for example:
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
I count all defined vars with $arr = get_defined_vars();
How can I count number of vars - in his case number of all arrays?
I used foreach, but maybe I don't do this properly.
$i = 0;
foreach ($arr as $value) {
$i++;
echo '<br>';
foreach ($value as $val) {
echo $val.',';
}
}
echo $i;
I don't know why result is 8 :/
Try this:
<?php
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$variable_s = 'adsfadfdfa';
$variable_n = 22;
$vararr = get_defined_vars();
// We want to exclude all the superglobals
$globalarrays = array(
'GLOBALS',
'_SERVER',
'_POST',
'_GET',
'_REQUEST',
'_SESSION',
'_COOKIE',
'_ENV',
'_FILES'
);
$narrays = 0;
foreach($vararr as $key => $variable) {
if ( !in_array($key, $globalarrays) && is_array($variable) ) {
echo $key . ' is an array<br />';
$narrays++;
}
}
echo '# arrays = ' . $narrays;
Notes:
The code counts only arrays, no scalars (is_array()).
It excludes the super global arrays like GLOBALS, _POST, etc.
Result:
number_one is an array
number_two is an array
number_three is an array
number_four is an array
# arrays = 4
it is all because, get_defined_vars() returns certain predefined indexes like GLOBALS, _POST, _GET, _COOKIE, _FILES and other indexes which are user defined, here in your case, those are number_one, number_two, number_three and number_four
for more details on get_defined_vars() you can refer the link
As the user defined indexes, are only after predefined indexes, you can use array_slice to slice your defined array.
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$arr = get_defined_vars();
$arr = array_slice($arr, 5, count($arr));
echo count($arr);
This prints the 4.
The function get_defined_vars() gets all of the variables that are defined currently in the server including environment and server variables.
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$arr = get_defined_vars();
print_r($arr);
Try this code and see the output in your browser. I'm sure you'll get to know how many variables are actually defined(including those defined by you)
For Reference: http://php.net/manual/en/function.get-defined-vars.php
I need to return multiple values from a function, therefore I have added them to an array and returned the array.
<?
function data(){
$a = "abc";
$b = "def";
$c = "ghi";
return array($a, $b, $c);
}
?>
How can I receive the values of $a, $b, $c by calling the above function?
You can add array keys to your return values and then use these keys to print the array values, as shown here:
function data() {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
return $out;
}
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
you can do this:
list($a, $b, $c) = data();
print "$a $b $c"; // "abc def ghi"
function give_array(){
$a = "abc";
$b = "def";
$c = "ghi";
return compact('a','b','c');
}
$my_array = give_array();
http://php.net/manual/en/function.compact.php
The data function is returning an array, so you can access the result of the function in the same way as you would normally access elements of an array:
<?php
...
$result = data();
$a = $result[0];
$b = $result[1];
$c = $result[2];
Or you could use the list() function, as #fredrik recommends, to do the same thing in a line.
<?php
function demo($val,$val1){
return $arr=array("value"=>$val,"value1"=>$val1);
}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>
$array = data();
print_r($array);
From PHP 5.4 you can take advantage of array dereferencing and do something like this:
<?
function data()
{
$retr_arr["a"] = "abc";
$retr_arr["b"] = "def";
$retr_arr["c"] = "ghi";
return $retr_arr;
}
$a = data()["a"]; //$a = "abc"
$b = data()["b"]; //$b = "def"
$c = data()["c"]; //$c = "ghi"
?>
Maybe this is what you searched for :
function data() {
// your code
return $array;
}
$var = data();
foreach($var as $value) {
echo $value;
}
In order to get the values of each variable, you need to treat the function as you would an array:
function data() {
$a = "abc";
$b = "def";
$c = "ghi";
return array($a, $b, $c);
}
// Assign a variable to the array;
// I selected $dataArray (could be any name).
$dataArray = data();
list($a, $b, $c) = $dataArray;
echo $a . " ". $b . " " . $c;
//if you just need 1 variable out of 3;
list(, $b, ) = $dataArray;
echo $b;
//Important not to forget the commas in the list(, $b,).
here is the best way in a similar function
function cart_stats($cart_id){
$sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
$rs = mysql_query($sql);
$row = mysql_fetch_object($rs);
$total_bids = $row->total_bids;
$sum_bids = $row->sum_bids;
$avarage = $sum_bids/$total_bids;
$array["total_bids"] = "$total_bids";
$array["avarage"] = " $avarage";
return $array;
}
and you get the array data like this
$data = cart_stats($_GET['id']);
<?=$data['total_bids']?>
All of the above seems to be outdated since PHP 7.1., as #leninzprahy mentioned in a comment.
If you are looking for a simple way to access values returned in an array like you would in python, this is the syntax to use:
[$a, $b, $c] = data();
I think the best way to do it is to create a global var array. Then do whatever you want to it inside the function data by passing it as a reference. No need to return anything too.
$array = array("white", "black", "yellow");
echo $array[0]; //this echo white
data($array);
function data(&$passArray){ //<<notice &
$passArray[0] = "orange";
}
echo $array[0]; //this now echo orange
This is what I did inside the yii framewok:
public function servicesQuery($section){
$data = Yii::app()->db->createCommand()
->select('*')
->from('services')
->where("section='$section'")
->queryAll();
return $data;
}
then inside my view file:
<?php $consultation = $this->servicesQuery("consultation"); ?> ?>
<?php foreach($consultation as $consul): ?>
<span class="text-1"><?php echo $consul['content']; ?></span>
<?php endforeach;?>
What I am doing grabbing a cretin part of the table i have selected. should work for just php minus the "Yii" way for the db
The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.
In the following code, I've accessed the values of the array with the print and echo constructs.
function data()
{
$a = "abc";
$b = "def";
$c = "ghi";
$array = array($a, $b, $c);
print_r($array);//outputs the key/value pair
echo "<br>";
echo $array[0].$array[1].$array[2];//outputs a concatenation of the values
}
data();
I was looking for an easier method than i'm using but it isn't answered in this post. However, my method works and i don't use any of the aforementioned methods:
function MyFunction() {
$lookyHere = array(
'value1' => array('valuehere'),
'entry2' => array('valuehere')
);
return $lookyHere;
}
I have no problems with my function. I read the data in a loop to display my associated data. I have no idea why anyone would suggest the above methods. If you are looking to store multiple arrays in one file but not have all of them loaded, then use my function method above. Otherwise, all of the arrays will load on the page, thus, slowing down your site. I came up with this code to store all of my arrays in one file and use individual arrays when needed.
Your function is:
function data(){
$a = "abc";
$b = "def";
$c = "ghi";
return array($a, $b, $c);
}
It returns an array where position 0 is $a, position 1 is $b and position 2 is $c. You can therefore access $a by doing just this:
data()[0]
If you do $myvar = data()[0] and print $myvar, you will get "abc", which was the value assigned to $a inside the function.
At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!
$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo $hello . $counter . "<br>";
}
It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:
$foo = "bar";
$baz = "foo";
echo $$baz; // will print "bar"
$foofoo = "qux";
echo ${$baz . 'foo'}; // will print "qux"
For more info, see the PHP documentation on variable Variables.
However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?
$hello = array(
"hello1",
"hello2",
// ... etc
);
foreach($hello as $item) {
echo $item . "<br>";
}
Try ${"hello" . $counter}
$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};
// output: world
You can use variable variables as:
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo ${'hello' . $counter } , '<br>';
}
as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.
<?php
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>
so this is enough to get the output as you want.
the output will be:-
hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...