$a = 'i am a $b'; // declared before $b is declared
function x(....) {
global $a;
$b = 'boy';
$c = '{$a}'; // i know this doesn't work. how can I make it work?
}
I want $c to return "i am a boy"
This is a simple example of my issue. In the real case, there are many variables involved. Is there a simple fix?
This is where functions come in handy. They take in the parameters and return some compiled value.
// create named function
function namedFn($b) {
return "i am a $b";
}
// or anonymous
$f = function ($b) {return "i am a $b"; };
// call function and pass $b as argument
$b = 'boy';
echo namedFn($b);
echo $f($b);
If you really need to reparse some string with the contents of your variables, just use str_ireplace
$a = 'i am a $b';
echo str_ireplace('$b', $b, $a); // $search , $replace , $subject
How could I access specific parameter from a function, example:
function someFunction()
{ echo $a = 7;
echo $b = 70;
}
someFunction();//770
How can I return only $a or $b, is possible ?
echo vs return
First of all, I think it is important to note that echo and return have very different behaviors and are used in very different contexts. echo simply outputs whatever is passed to it, either to an html page, or to the server log.
<?php
$a = 5;
function printFoo() {
echo 'foo';
}
echo '<h1>Hello World!</h1>'; // prints an h1 tag to the page
echo $a; // prints 5 to the page
foo(); // prints foo to the page
?>
return on the other hand is used to "[end] execution of the current function, and return its argument as the value of the function call." return can only ever take one argument. It can also only be executed once in a function; once it is reached, the code will jump out of the function back to where the function was invoked.
<?php
function getFoo() {
return 'foo';
}
// print the value returned by getFoo() directly
echo getFoo();
// store it in a variable to be used elsewhere
$foo = getFoo(); // $foo is now equal to the string 'foo'
function getFooBar() {
return 'foobar'; // code beyond this statement will not be executed
echo 'something something';
return 'another foobar';
}
echo getFooBar(); // prints 'foobar'
?>
function paramters
As it stands, someFunction can only return $a or $b or an array containing $a and $b, which may become a problem if, say, you need to print out $c. To make the function more reusable, you can pass it an argument and then reuse the function wherever you like.
<?php
function printSomething($myVar) {
echo $myVar;
}
$a = 7;
$b = 70;
$c = 770;
printSomething($a) . '\n';
printSomething($b) . '\n';
printSomething($c) . '\n';
printSomething(7000); // you don't have to pass it a variable!
// Output:
// 7
// 70
// 700
// 7000
?>
If you wish to return only one parameter then you just use the return statement.
<?php
function someFunction()
{
$a = 7;
$b = 70;
return [$a, $b];
}
$arrayS = someFunction();//array containing $a and $b
echo $arrayS[0]."\n";
echo $arrayS[1]."\n";
echo "\n";
echo "Another way to access variables\n";
echo someFunction()[0]."\n";
echo someFunction()[1]."\n";
I'm wondering if this was possible and I could not find a way to do it so I ask. How can I get the name of the variable where in a instance of a class is present.
Pseudo code:
class test{
public $my_var_name = '';
function __construct(){
//the object says: Humm I am wondering what's the variable name I am stored in?
$this->my_var_name = get_varname_of_current_object();
}
}
$instance1 = new test();
$instance2 = new test();
$boeh = new test();
echo $instance1->my_var_name . ' ';
echo $instance2->my_var_name . ' ';
echo $boeh->my_var_name . ' ';
The output would be like:
instance1 instance2 boeh
Why! Well I just wanna know its possible.
I have no idea why, but here you go.
<?php
class Foo {
public function getAssignedVariable() {
$hash = function($object) {
return spl_object_hash($object);
};
$self = $hash($this);
foreach ($GLOBALS as $key => $value) {
if ($value instanceof Foo && $self == $hash($value)) {
return $key;
}
}
}
}
$a = new Foo;
$b = new Foo;
echo '$' . $a->getAssignedVariable(), PHP_EOL; // $a
echo '$' . $b->getAssignedVariable(), PHP_EOL; // $b
I created this code trying to answer for How to get name of a initializer variable inside a class in PHP
But it is already closed and referenced to this question,
just another variant easy to read, and I hope I didn't break any basic concept oh php development:
class Example
{
public function someMethod()
{
$vars = $GLOBALS;
$vname = FALSE;
$ref = &$this;
foreach($vars as $key => $val) {
if( ($val) === ($ref)) {
$vname = $key;
break;
}
}
return $vname;
}
}
$abc= new Example;
$def= new Example;
echo $abc->someMethod();
echo $def->someMethod();
I can't find a good reason to do that.
Anyways, one way you can do (but again it has no use as far as i can imagine) this is by passing the instance name as a constructor's parameter, like this:
$my_instance = new test("my_instance");
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.
For example:
A.php (the config file):
<?php
$a = array('name'=>'wine[$index][name]',
'value'=>'wine[$index][value]'
)
?>
B.php:
include_once(a.php)
...
//for simple
$index = 0;
$b = $a;
//actual code like
foreach($data as $index=>$value)
$b += $a
I know this example won't work, just for explaination, i wanna if it is possible (if possible, how?) to delay variable $index to take value when $b = $a ?
make "a" a function
function a($index) { global $data; return $data[$index] ... }
$b = a($index);