I am trying to loop through a JSON Object (DATA) containing three nested JSON Objects (NEWUSERS,NEWUSERDATA,NEWRELATIONS), using a switch function to choose the appropriate function for a MySQL insert. Each function housed in the switch is called once as I loop through the keys, but they ALL seem to only ever receive the NEWRELATIONS object. Consequently, the functions fail with the exception of insertNewTestRelations, the function intended to receive the NEWRELATIONS object. I think the answer must be staring me in the face, but can anybody think why the JSON object is being reused?
Reading and iterating JSON
$json=json_decode($_SERVER['HTTP_JSON'],true);
$data=$json['DATA'];
foreach($data as $key=>$json_obj){
$result=null;
$result=$db->insertNewSwitch($key,$json_obj,$last_sync);
$response[$key.":errors"]=$result['errors'];
$response[$key.":successes"]=$result['successes'];
}
Switch function
public function insertNewSwitch($key,$json_obj,$last_sync){
$result;
if($key="NEWUSERS"){
$result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
}
if($key="NEWUSERDATA"){
$result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
}
if($key="NEWRELATIONS"){
$result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
}
return $result;
}
Try using else in your logical operator for the switch, and also double equals for comparisons
public function insertNewSwitch($key,$json_obj,$last_sync){
$result;
if($key=="NEWUSERS"){
$result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
}
else if($key=="NEWUSERDATA"){
$result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
}
else if($key=="NEWRELATIONS"){
$result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
}
return $result;
}
You are using = not ==. This is most likely your problem.
Because you are assigning the values, it will evaluate to true each time, so each statement will be entered.
Related
I am confused about return statement , why we need to use return in end of function , for example
function test($a){blah;
blahh ;
blahhh;
blahhhhh;
return;}
What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the use of return (when we not returning any value).
It depends on what you're trying to achieve.
If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.
I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
return 10;
}
$a = test(); // $a stores the value 10
echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.
For further reference, check What is the difference between PHP echo and PHP return in plain English?
In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.
Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.
"return" is important when you plan to call this function from other codes, it helps you to:
Know if the function works correctly, or not.
Obtain values from a function.
Make sure other codes are not executed after return.
It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
if(file_exists($a)){
if(is_file($a)){
return $a." IS A FILE\n";
} else if(is_dir($a)) {
return $a." IS A DIR\n";
} else {
return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
}
} else {
return $a." NOT EXISTS\n";
}
return 0;
}
$filecheck = test("/abc/def.txt");
if($filecheck){
echo $filecheck;
} else {
echo "unknown error";
}
Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
blah;
blahh;
blahhh;
blahhhhh;
return 1;
}
So I know the code is running to last line.
Otherwise the function just finishes silently.
It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {
switch($who) {
case 'John':
return 'apple';
case 'Peter':
return 'Rhubarb';
}
}
So, considering the following:
$WhatPie = FavouritePie('John');
echo $WhatPie;
would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back. Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer, if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no. But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called. If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.
This may seem like a simple question but I have searched for an answer and come across call backs and a few different things but surely there is a simple way to do this.
I have a function in a class
that uses an iterative process so i end up with an array:
$msg[$i]
I want to exit the function with that array returned to main script
exit($msg[])
but will only return for example $msg[1] or $msg[$i] the last iteration I'd like to get the whole array without manually typing each one defeats the point of the iterative process
use return instead exit
return $msg;
have you tried using return $msg; ?
In order to return an array, you return the variable name of the array. This is really a pointer to the first element in the array.
This is an example of how to return an array:
function dofoo() {
$msg["a"] = "Foo";
$msg["b"] = "Bar";
$msg["c"] = "Baz";
return $msg;
}
$returned_array = dofoo();
Under the hood what happens is: return $msg; returns a pointer to the first element of the array. $returned_array = dofoo(); allocates enough memory for the returned array and stores it in $returned_array.
Is it possible to return a loop? not the result but the loop it self.
I want to create a function in php. For example like this.
function myloop($sql){
$query = mysql_query($sql);
return while(mysql_fetch_assoc($query))
}
The reason i want to create this is for me to avoid repeating code. Anyone can help me? Thank you..
No, but you can simulate that with an Iterator for stable released PHP as of today. In PHP 5.5 there will be generators that is close, too.
$lazyQuery = new SqlResultItertor($sql);
foreach ($lazyQuery as $assoc) {
$assoc; # the result, one per row
}
BTW: PDO and MySqli offer this already out of the box (not lazy query, but the result is traversable), for mysql you need to write such an iterator-result object your own.
For some mysql_* functions related code, see this answer. However the general suggestion as of today is to use PDO or mysqli instead, those offer more out of the box. See How to successfully rewrite old mysql-php code with deprecated mysql_* functions?
No, you can't. You can pass a function to a function, though:
// The myloop function, with another name.
function query($sql, $rowcallback)
{
$query = mysqli_query($sql); // use mysqli, not mysql
while
( ($row = mysql_fetch_assoc($query)) &&
call_user_func($rowcallback, $row) );
}
// The code to process a row.
function processRow(array $row)
{
// Use your row here..
var_dump($row);
return true; // You can return false to break processing.
}
//calling:
query($yourSelf, 'processRow');
Instead of passing the function by name, you can also use anonymous functions, depending on your php version:
//calling:
query($yourSelf,
function(array $row)
{
var_dump($row);
return true; // You can return false to break processing.
});
The function which is called from the callee is often called a callback. call_user_func is the best way to call a callback, since it will also accept methods and static methods, not just functions, so you're more flexible.
No, it isn't.
You can return a function to does nothing but run a loop, but you can't return the loop itself.
No.
You could, for instance, return an anonymous function which may contain a loop, but you can only return values from functions, not language constructs.
You should turn it inside out!
Instead of returning the loop, you could do it this way using Variable functions :
function myloop($sql, $myFunction){
$query = mysql_query($sql);
while(mysql_fetch_assoc($query)) {
$myFunction($result);
}
}
function doSomethingWithTheResult($result) {
echo $result; // just to have something here...
}
//now the usage:
myloop("SELECT 1", 'doSomethingWithTheResult');
With a squint, this is similar to the concept of the Template method OOP design pattern.
No, but you could do
function loopdate($sql,$code)
{
$query=mysql_query($sql)
while (mysql_fetch_assoc($query))
{
eval($code);
}
}
However - eval is rediculously dangerous its really really discouraged.
function loopdate($sql,$function)
{
$query=mysql_query($sql)
while ($data=mysql_fetch_assoc($query))
{
$function($data);
}
}
would be better.
myfunc($data)
{
foreach ($data as $key->$value)
{
print "<tr><td>".$key."<td><td>".$value."</td></tr>\n";
}
}
So you can call
loopdate("select * from mytable","myfunc");
In PHP 5.5+ it is possible, using the yield keyword instead of return (this is called a generator):
function myloop($sql) {
$query = mysql_query($sql);
while (($row = mysql_fetch_assoc($query))) {
yield $row;
}
}
foreach (myloop('SELECT * FROM foo') as $row) {
// do something with $row
}
This is not much different from what you could do with iterators in older PHP, but the code is much cleaner.
I have the following PHP function
function newUser($username, $password) {
$checkUsernameAvailablity = check($username);
if (!$checkUsernameAvailablity)
{
return -1;
}
$checkPasswordComplexity = checkpass($password);
if (!$checkPasswordComplexity)
{
return -2
}
}
I would like to know if the username is taken and the password is not complex enough, will PHP stop the function after it returns -1 or will it continue and return -2 also.
Thanks in advance,
RayQuang
When execution reaches a return statement, the function will stop and return that value without processing any more of the function.
return statement returns the value and terminates the execution of the function. If the return is hit, no further code is executed in that body.
By the way, not all code paths have return values.
the design of your function is wrong.
I would return different values when the function ends accordingly.
For multiple returns I would use switch or a properly designed IF statements.
Or better return an associative array.
Is there a way to check if an object has any fields? For example, I have a soap server I am querying using a soap client and if I call a get method, I am either returned an object containing fields defining the soap query I have made otherwise I am returned object(stdClass)#3 (0) { }.
Is there a way to tell if the object has anything?
public function get($id){
try{
$client = new soapclient($this->WSDL,self::getAuthorization());
$result = $client->__soapCall('get', array('get'=> array('sys_id'=>$id)));
if(empty($result)){$result = false; }
}catch(SoapFault $exception){
//echo $exception;
$result = false;
}
return $result;
}//end get()
This method should return either an object or false and I am only receiving an object with no fields or an object with fields.
Updated to reflect current behavior, 5/30/12
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {
...
One of the user contributed code on the php empty() page which I think addresses your problem of checking if the array is filled but has empty values.
http://www.php.net/manual/en/function.empty.php#97772
To find if an array has nothing but empty (string) values:
<?php
$foo = array('foo'=>'', 'bar'=>'');
$bar = implode('', $foo);
if (empty($bar)) {
echo "EMPTY!";
} else {
echo "NOT EMPTY!";
}
?>