I have class for take values inside loop as this :
$db_user->take_phone[1];
Inside loop I need take different values for the class
$a=array("phone","name","street");
foreach($a as $aa) {
echo $db_user->take_'$aa.'[1]
}
As you can see inside the loop I need to change the value inside take_$string, but it doesn't work. I suppose there is a syntax error but I'm not sure. How can I write this to work correctly.
I've tried different ways but haven't found a solution.
You can use a variable variable, which takes the form of $var->$property. Notice the extra $.
$a = array("phone","name","street");
foreach($a as $aa) {
$var = "take_$aa";
echo $db_user->$var[1];
}
Demo: https://3v4l.org/HolHZ
You have errors php syntax. I has explained it in my example more:
<?php
$db_user = new stdClass();
$db_user->take_phone = [
'p1','p2','p3'
];
$db_user->take_name = [
'n1','n2','n3'
];
$db_user->take_street = [
's1','s2','s3'
];
$a=array("phone","name","street");
foreach($a as $aa) {
echo $db_user->{'take_'.$aa}[1];
}
Related
I have a problem.
I have written a web site where there are two PHP files where 1st contains variables and one array and next one contains next array with variables. Variables of second file are url adress. And now I need to know, if I can make something like:
with foreach
foreach($array01 as $word) {
$a = 0;
echo '<a href="'. $array_url[$a] .'><li>'.$word.'</li></a>';
$a = $a + 1;``
}
Output:
<li>var01</li>
<li>var02</li>
with foreach:
foreach ($array01 as $word) {
$a = 0;
echo '<li>'.$word.'</li>';
$a = $a + 1;
}
I know it does not works with this example but maybe there is a way to make it correct.
The problem in your code is that you're doing $a = 0; at the beginning of each loop. That undoes the $a = $a + 1; that you do at the end, so you're using $array_url[0] every time. You can fix that by putting $a = 0; before the loop instead of inside it.
But instead, you can tell foreach to give you the array indexes as well as the values. Then you can use that index to access the other array.
foreach ($array01 as $i => $word) {
echo '<a href="'. $array_url[$i] .'><li>'.$word.'</li></a>';
}
your question is unclear, you must specify your arrays
BUT
i think you should use for instead of foreach
for($a=0; $a < count($array01); $a++)
{
echo '<a href="'. $array_url[$a] .'><li>'.$array01[$a].'</li></a>';
}
What your asking is unclear but as I've understood from your question, you want to take an array of urls from a PHP file into another PHP file and output them as link in the HTML format.
If that's the case then follow this:
Your 2nd PHP file should look like this as far as I can guess::
<?php
//some codes..
$arrayofvariables=["word" => "url_address",....]; //your array of url address
//some codes..
?>
And in your 1st file do something like this::
<?php
include 'pathtoyour2ndfile'; // include your 2nd file with url array
foreach($arrayofurladdress as $word => $url_address){
echo "<li>$word</li>";
}
I could not figure what is the use of the variables and array in the first file. So, If this isn't what you're looking for please try to clarify your question by improving your English or upload all the content of your PHP files in the question.
Thanks. And A Happy New Year 2016. Hope my answer helps you. If it does don't forget to rate it and mark as answer.
Try This
$a = 0;
foreach ($array01 as $word) {
echo '<li>'.$word.'</li>';
$a++;
}
if your $array_url is like
$array_url = [ 'var_url01' , 'var_url02', 'var_url03'] ;
and your $array01 is like
$array01 = [ 'var01' , 'var02' , 'var03'];
then you can use the foreach loop as
foreach ($variable as $key => $value) {
echo '<li>'.$word.'</li>';
}
I have this case when I have array_push inside function and then I need to run it inside foreach filling the new array. Unfortunately I can't see why this does not work. Here is the code:
<?php
$mylist = array('house', 'apple', 'key', 'car');
$mailarray = array();
foreach ($mylist as $key) {
online($key, $mailarray);
}
function online($thekey, $mailarray) {
array_push($mailarray,$thekey);
}
print_r($mailarray);
?>
This is a sample function, it has more functionality and that´s why I need to maintain the idea.
Thank you.
PHP treats arrays as a sort of “value type” by default (copy on write). You can pass it by reference:
function online($thekey, &$mailarray) {
$mailarray[] = $thekey;
}
See also the signature of array_push.
You need to pass the array by reference.
function online($thekey, &$mailarray) {
My Php function loops trough the mysql table and for each row it sets the row name as $var and the row value to $val.
foreach($row as $var => $val) {...
Now I want to set the received rowname ($var) as a new variable.
This example is not right but to explain my thoughts ; $name$var = $val
If $var would be = rowname1
then the new variable would be $rowname1 = value1
Any ideas how to achieve this ?
Thanks.
You can use variable variables to do that:
foreach(...) {
$$var = $val;
}
But cleaner would be to use an array:
foreach(...) {
$var_names[] = array($var => $val);
}
<?php
$array = array(
'go' => 'something1',
'go2' => 'something2',
'go3' => 'something3',
'go4' => 'something4',
'go5' => 'something5',
);
foreach ($array as $key => $val) {
${$key} = $val;
}
print $go;
?>
EXAMPLE
or you could use the $$ way explained here:
Read more about Variable Variables...
You can use it like ${$var} = $val. Curly brackets are there just for convenience and readability. $$var = $val should also work.
You can create variables with dynamic names on the fly using strings! This is supported in the documentation provided here
A quick example:
// This now holds the string hello
$variableName = 'hello';
// This creates the variable 'hello' and contains the value test
$$variableName = "test";
echo $hello;
With the above example complete you will be able to create a variable name with the key + value strings as follows:
$count = 1;
foreach($row as $var => $val)
{
$varName = $var.$count;
$$varName = $val;
$count++;
}
This will create column_name1, column_name2 etc.
I feel the need to add a little discretion as this is not common or best practice. The best way to handle this information would be to take the $key => $val pair and store it into a separate variable or parse through them. By doing this you are basically throwing away all of the ease of use that is using arrays.
Also, side note:
You can also dynamically call on methods this way.
function test()
{
echo "test yar";
}
$method = "test";
$method();
I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.
Please help in code that i am unable to print values of associative array after extracting itself
class display{
protected $variables = array();
function set($name,$value) {
$this->variables[$name] = $value;
}
function render(){
extract($this->variables);
// ?? to print values of $variable array
}
foreach($this->variables as $key => $value) {
echo "{$key}: {$value}\n";
}
And how do you try to print the values? The array itself (it's $varables, not $variable, btw) should not be affected.
Update: For what I can tell by your reply to the other answer, you do not really need to extract array. extract jusst puts the variables into local namespace where they will be harder to enumerate. What you need is to use array as is.
foreach($this->variables as $k => $v) echo "$k: $v\n";
or whatever you want to do with them.
if you are using classes, u will need to have something like
var $variables = array(); or
public $variables = array();
and if you are using structured , you will need to do
global $variables;
inside the function .. but as u are using $this-> it indicates ur using a class. You will have to put in some more code in here to make the situation clear.