How to assign an array to variable in php - php

I have a function with a reference parameter. The function populates the reference with an array. When it returns I test the reference value with a print_r(). It's successful. But when I try and assign it to another var as in,
$_SESSION['allvats'] = $ref_all_vats;
I get an empty session var. How do I assign this? I've tried declaring the reference as an array before invoking the function and also assigning to sessions as
$_SESSION['allvats'][] = $ref_all_vats;
Thank you.
Edit.
Session is running. Other SESSION vars populate. Here is the code bit:
if(buildMetalArrayNsp($process_id, $ref_all_vats)) {
writeDataToFile("vats " . print_r($ref_all_vats, true), __FILE__, __LINE__);
$_SESSION['allvats'] = $ref_all_vats;
}
Here is the session code:
$lifetime= 60 * 60 * 24 * 30; // 30 days
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

Try like this
session_start();
$_SESSION['allvats'] = $ref_all_vats;

list($firstVar, $secondVar) = explode(' ', 'Foo Bar');
list() is what you are after.

Your code is fine, there is something else going wrong. Are you sure the if statement is evaluating to true? Whenever you are tracking down errors it is good to use echo or print_r quite a bit. For example:
echo "<pre>Above if\n";
if(buildMetalArrayNsp($process_id, $ref_all_vats)) {
echo "In if\n";
$_SESSION['hello'] = "world";
$_SESSION['allvats'] = $ref_all_vats;
}
echo "Below if\n";
echo "\n-----------------------\n";
echo $_SESSION['hello'];
echo "\n-----------------------\n";
print_r($_SESSION['allvats']);
echo "\n-----------------------\n";
print_r($ref_all_vats);
echo "</pre>";
Of course if you are not displaying to a web page remove the <pre> tags.

Related

How to assign a session value to a variable

I have a session which I need to assign to a variable to be used on Stored Procedure. But cant seem to get the variable being affected on it
I have already tried the following, but nothing
1)
ob_start();
echo $_SESSION['User'];
$userV = ob_get_contents();
ob_end_clean();
2)
$userV = $_SESSION['User'];
3)
$userV= echo $_SESSION['User']; //fails as echo, used print instead
4)
$userV= print $_SESSION['User'];
But when I use a know value like below it works
$userV= 41;
The intended Procedure as follows:
$sql="CALL sp_getUser('$userV')";
The second one is the correct one: $userV = $_SESSION['User'];.
If $userV does not hold the expected value after this assignment, two things can be the reason: You haven't initialized the session (session_start()) or the you haven't set the $_SESSION["User"] (somewhere in another script you should have something like $_SESSION["User"]=41;.
You can test what is in the $_SESSION-variable presently by print_r($_SESSION);

How to assign the echo statement from a function call to a variable?

I am trying to get the echo of a function and add the value into a variable.
So this is what I've done.
function myfunction() {
echo 'myvar';
}
Then I want to get it into a variable like this:
$myVariable = myfunction();
I thought this would work but I isn't working.
Is this not the way to do this? If not, how do I do this?
You can call the function, while you have output buffering turned on and then you can capture the output. E.g.
<?php
ob_start();
myfunction();
$variable = ob_get_contents();
ob_end_clean();
echo $variable;
?>
output:
myvar
Or you simply change the echo statement into a return statement.
Your current version doesn't work, because you don't return the value from your function. And since you omitted the return statement the value NULL gets returned and assign to your variable. You can see this by doingthis:
$variable = myfunction();
var_dump($variable);
output:
NULL

How to equate an echo value to a variable and access that variable somewhere else

I want to echo a value, but hold it as a variable to access that value later.
What's the right syntax for the following?
if (!empty($row['A'])){
$Test = echo '<span>sale</span>';
}
How do i prevent the above PHP block from printing and only print when that variable when is called somewhere like as in.
echo $test;
Is there a way to put function inside echo?
like.
echo 'echo this is a 'if (!empty($row['A'])){
$Test = echo '<span">function</span>';
}''.
I know the above is wrong, please give a reason for your downvote if you are gonna downvote. Thanks.
You don't need to store echo in the variable. When you want to use the variable later, that is when you call echo. Your code should look like:
$test = (!empty($row['A'])) ? 'sale' : '';
This is a ternary operator which is basically a shorthand for the following if/else:
if(!empty($row['A'])) {
$test = 'sale';
} else {
$test = '';
}
In this case, I set it to an empty string if $row[a] is empty so nothing bad happens if you echo it later. (You want to make sure your variable is defined no matter what, so you don't cause an error by trying to call an undefined variable.)
Then, to use it, simply call
echo $test;
Why do you want to put the function inside of an echo? That defeats the point of storing a variable in the first place.
I think what you would want is something like this:
echo "This is a " . returnValue();
function returnValue() {
return "function";
}
The function is now set to return the value "function", in the echo we echo some text and the return value, so what it should echo is: "This is a function"
Assuming you're trying to check if the given variable is empty and then store some text in it, the correct syntax would be:
if (!empty($row['A'])){
$test = '<span>sale</span>';
}
The above code reads: if $row['A'] is not empty, store $test equal to the string given.
Now, you can re-use the variable in your code.
I'm not quite sure what you're trying to accomplish with the second code block, but I assume you're trying to echo the variable value only if it's set. In that case, you can use the isset() function:
echo isset($test) ? $test : '';
This is the shorthand for the following:
if (isset($test)) {
echo $test;
} else {
echo '';
}
First of all, you should do some tutorials and read up on the basics. That said here is what I think you're looking for. For one thing you never do $var = echo 'blah';
First example.
if (!empty($row['A'])){
$Test = '<span>sale</span>';
echo $Test;
}
Then you can use $Test later in the code if you want. To avoid it echoing just remove the echo $test and do it elsewhere.
For your second part using a variable and a ternary is the best option for this
$isItEmpty = empty($row['A']) ? 'empty' : 'not empty';
echo 'This is row is '.$isItEmpty;
You can also to a ternary inline like this, but it's cleaner to use a variable usually.
echo 'This is row is '.(empty($row['A']) ? 'empty' : 'not empty');
This would output: "This row is empty" if it's empty and "this row is not empty" if it's not (both examples would have the same output.
Hope this helps
You don't need to include the echo in the variable.
Where you have
$Test = echo '<span>sale</span>';
Instead have
$Test = '<span>sale</span>';
Then when you want to echo it, simple
echo $Test;
If you would like to echo it according to the if then you can:
if (!empty($row['A'])){
$Test = '<span>sale</span>';
echo $Test;
}

PHP Array issue when looping and echoing

I'm having trouble getting the array to work right, let me show you the code here
function scanArray(){
$al = sizeof($_userLoaders);
echo $al. "<br />";
for ($tr = 0; $tr <= $al; $tr++) {
echo "value: " .$tr. "<br />";
echo $_userLoaders[$tr];
}
}
//Fetch user's loaders.
$_userLoaders;
function get_user_loaders(){
$con = connectToMySQL();//connects to my_sql
mysql_select_db("my_database", $con);//connect database
$t = mysql_query("SELECT * FROM someTable
WHERE value_a=".$_SESSION['value_a']." AND value_b=someValue");
$x= 0;
//lets loop through the results and create an array to compare later.
while ($result = mysql_fetch_array($t)){
$_userLoaders[$x] = $result['value_c'];
$x++;
}
//lets get all the options for
print_r($_userLoaders);//this part prints what it should
scanArray();
}
okay, I minimized the code above to show you what's going on. Pretty much function get_user_loaders() works great. It fetches data from a table in a database, and returns what it should. Second, it makes an array out of it. Again, this part works great. When the print_r() method is called it prints what it should, here's an example of what it prints:
Array ( [0] => tableValue )
yes, at this point it only has one value, please note that this value can vary from no values to 100 values which is why I am using an array. In this case, i'm testing it with one value.
Now, once I call scanArray() It doesn't echo the values.
the scanArray() function echoes the following:
0
value:
so what I don't understand is why does it print it out, but it doesn't display the function? Thanks in advance.
Your problem is that $_userLoaders variable is declared outside the function and function scanArray knows nothing about it. You need to either pass that variable in as a parameter:
function scanArray($_userLoaders) {
...
}
with the call at the end being
scanArray($_userLoaders);
or alternatively declare the variable as global inside the function:
function scanArray($_userLoaders) {
global $_userLoaders;
...
}
That would be because $_userLoaders is not equal to anything inside your scanArray() function. While it's not good practice, you can add the line:
global $_userLoaders;
to your scanArray() function and every other function that uses that global variable then, and it should work.

Getting object variable using string + variable

I would like to do something like this:
echo $myObject->value_$id but I don't know proper syntax and I'm not sure if it is possible.
$id is some PHP variable, for example has value 1. In the end, I would like to get $myObject->value_1 but the number part (1) should be dynamic.
The feature is called variable properties:
<?php
$myObject = (object)NULL;
$myObject->value_1 = 'I am value nr 1';
$id = 1;
echo $myObject->{"value_$id"};
This works:
$variableName = 'value_whatever_1337';
echo $myObject->$variableName;
$name = "value_" . $id;
echo $myObject->$name;

Categories