How can I echo the value returned from a function, called within another function in PHP.
For example, if I have function like this:
function doSomething($var) {
$var2 = "someVariable";
doSomethingElse($var2);
}
function doSomethingElse($var2) {
// do anotherSomething
if($anotherSomething) {
echo "the function ran";
return true;
}
else {
echo "there was an error";
return false;
}
}
I want to echo the echo from the second function inside the first. The reason is because the second function can produce a string when it fails that the first cannot.
So how would I output the returned value from the second function?
Create an array containing values that you would like to return and then return that array.
function doSomethingElse($var2) {
// do anotherSomething
if($anotherSomething) {
$response['message'] = "the function ran";
$response['success'] = TRUE;
}
else {
$response['message'] = "there was an error";
$response['success'] = FALSE;
}
return $response;
}
In your other function
$result = doSomethingElse($var2);
echo $result['message'];`
Related
I', trying to update a row on parse using PHP. I'm using this function:
if (isset($_GET['updateHistory']))
{
updateHistory($_GET['updateHistory']);
}
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}
function updateHistory($obId,$yesNo) {
$bool = "";
if ($yesNo == "YES") {
$bool = true;
} else {
$bool = false;
}
$query = new ParseQuery("TestObject");
try {
$history = $query->get($obId);
$history->set("isHistory", $bool);
$history->save();
} catch (ParseException $ex) {
echo "Error Updating History";
}
reload();
}
The problem now is I can't pass the 2nd variable which is $yesNo using
<a href='?updateHistory=$obId&yesNo=YES'>YES</a>
How can I pass the 2nd variable? thanks!
try
if (isset($_GET['updateHistory'], $_GET['yesNo'])) {
// you should sanitize your $_GET values before using them
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
Since your function depends on both variables being set, combine the if-statement to check both fields and do a single call to your function:
if (isset($_GET['updateHistory']) && isset($_GET['yesNo'])) {
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
You can then drop this part altogether:
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}
Guys i have this code:
class Test {
public function __construct($valore) {
if ($valore != TRUE ) {
return false;
} else {
return true;
}
}
}
and in another page this:
$test = new Test("");
if ($test) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
Why is all the time true??
Sorry and thank you!
Constructors don't have return values. So if you want a to test that value you need to have a method do this for you.
class Test
{
private $valore;
public function __construct($valore) {
$this->valore = $valore;
}
public function test() {
return (bool) $valore;
}
}
$test = new Test("");
if ($test->test()) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
Demo
It's always true because the $test object is always NOT false, it's an object. The return value of the constructor isn't what you're testing.
class Test {
var $valore;
public function __construct($valore) {
if ($valore != TRUE ) {
$this->valore = false;
} else {
$this->valore = true;
}
}
}
$test = new Test(FALSE);
if ($test->valore === TRUE) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){
$ERROR = array();
if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}
//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}
if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}
then when I run my code
$result = uploadEmploymentDoc(1, 2);
if($result !=array()){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Now my question is this. Why is my function running my code and not showing me an error when I upload an unsupported document type. Am I defining my foreach loop correctly? For some reason I cant get my errors back.
you should write like this-
if(is_array($result)){
foreach($result as $er){
echo $er."<br>";
}
} else {
//your code for handling error
}
You can get more info :http://us2.php.net/is_array
Try use
$result = uploadEmploymentDoc(1, 2);
if(!is_array($result)){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.
I am new to PHP, so I apologize if this looks like a mess... I am trying to validate a form using the following three functions - checkName, checkEmail, and checkMessage. The problem I am running into is when I submit the form, it always displays the first error, even if the input is correct. Can anyone tell me what I'm doing wrong?
function checkName(){
if($name == ''){
print "Please enter your name!<br />";
return false;
}
else{
if(strlen($name)<2) {
print "Your name should be more than 1 characters long!<br />";
return false;
}
else{
return true;
}
}
}
function checkEmail(){
if($from == '') {
print "Please enter your email address!<br />";
return false;
}
else{
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $from)){
print "Please enter a valid email address!<br />";
return false;
}
else{
return true;
}
}
}
function checkMessage(){
if($message == '') {
print "Please enter your message!<br />";
return false;
}
else{
if(strlen($message)<10) {
print "Your message should be more than 10 characters long!<br />";
return false;
}
else{
return true;
}
}
}
if($validation == ''){
$a = checkName();
$b = checkEmail();
$c = checkMessage();
$result = array($a, $b, $c);
return $result;
Pass the variables to test into your functions to check them. The way you have it now, it would assume you are using global variables for $name,$message,$email. That would require the use of the global keyword (or some other options) in the functions, but is considered poor practice. Best to pass the variables
Called as:
$a = checkName($name);
$b = checkEmail($email);
$c = checkMessage($message);
Definitions
// Pass variable to function
function checkName($name){
if($name == ''){
print "Please enter your name!<br />";
return false;
}
else{
if(strlen($name)<2) {
print "Your name should be more than 1 characters long!<br />";
return false;
}
else{
return true;
}
}
}
function checkEmail($email){
// etc...
}
function checkMessage($message){
// etc...
}
By the way, as someone who frequently has to maintain old PHP code written by others, I can tell you that it is highly recommended that you do not use variable names like $a,$b,$c. Instead make them readable like $nameResult, $emailResult, $messgeResult.
In the functions your variables are not defined. If they are defined at all you have to use global $variable in your functions to have them defined in your functions
example:
bad:
$var = 'Hello';
function fun () {return $var;}
echo fun () . ' world';
good:
$var = 'Hello';
function fun () {
global $var;
return $var;
}
echo fun () . ' world';