get results returned in a function - php

i have this inside a php function:
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
so its returning all of the values in the $result variable
when i do a print_r on the function, the results display like this:
stdClass Object
(
[domainname] => domain.com
[element] =>
[availability] => false
)
i am calling the function with this code:
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
so i tried to get the returned by doing $domain->availability but its not returning the value, example:
if($domain->availability) {
echo 'yes';
} else {
echo 'no';
}
am i trying to get the data the incorrect way?
UPDATE
the full function is:
if(!function_exists("domainNameCheck")) {
function domainNameCheck($domainName, $element) {
$result = '';
$client = new IcukApiClient();
$client->username = "username";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = "/domain/availability/" . $domainName;
$req->method = "GET";
$res = $client->send($req);
$availability = 'unknown';
if ($res->success) {
$obj = json_decode($res->response);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
}
}

Your main problem seems to be that you are calling a function with 2 parameters but passing only one parameter
function domainNameCheck($domainName, $element) {}
// called like this (one parameter)
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
This should be generating a compile error!
Also here
if ($res->success) {
$obj = json_decode($res->response);
// check what $obj->available is set to
// it may also be a string and not a boolean
print_r($obj);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}

Please note that there are two error/warning messages PHP is giving:
E_WARNING : type 2 -- Missing argument 2 for domainNameCheck()
E_NOTICE : type 8 -- Undefined variable: element
You should fix those errors, and make sure you are informed of errors during development.
Secondly, you have defined your availability as a string by assigning "false", "true", or "unknown". So when you do this:
if($domain->availability) {
... that will be true for all three values, because strings are true for PHP when converted to boolean (except when empty). To illustrate, this will echo "hello":
if ("false") echo "hello";
So you need to change your test like this:
if($domain->availability === "true") {
Or, If you want to define $domain->availability as a true boolean, then you need to alter the assignments in your function, like this:
....
$availability = $obj->available; // assuming that is a boolean!
}
else {
$availability = null; // unknown
}
... and then you can do what you had:
if($domain->availability) {

Likely because $domain->availability is boolean
To output you can first check whether its true or false and output accordingly
here's a simple example:
if ($domain->availability){
echo 'Available';
}
else {
echo 'Not Available';
}

Related

Why substr() doesn't work correctly with a number that has a leading zero?

I have this script:
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
//=> no
Demo
Why it prints no? I expect it prints yes. Because the value of $id starts with 0. What's wrong?
EDIT: In reality I'm passing $id like this: DecryptId($_POST['au']);. $_POST['au'] is containing a number. Something like these:
23
43552
0153
314
09884
As you see, sometimes that number starts with 0. And I need to pass it as a string. How can I do that?
Because of the leading zero, PHP will be parsing that number as octal. Even if it didn't do this, most languages will strip off the leading zeros (since they don't actually form part of the number). This means that $id will evaluate to 12.
Are you sure you don't want to declare it as a string? ($id = "014")
Your function is working fine the issue is that you are passing a number in your function when you should provide a string. So in the case that your variable type is integer the leading zero will eventually fly away.
You can add something to your function to check the variable type and inform the user.
function DecryptId($id) {
$type = gettype( $id );
if($type!= "string") {
echo "Your variable has type ".$type.". Use a 'string' type variable";
return;
}
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
echo "\n";
$id = '014';
echo DecryptId($id);
Try the above example in PHP Sandbox
try this
<?php
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = '014';
echo DecryptId($id);
?>

difference between Null and False

i watching tutorial about developing guestbook with php
this is the code that get the message with the id
public function GetMessage($id)
{
//Database
$id = (int)$id;
$gb_host = 'localhost' ;
$gb_dbname = 'guestbook' ;
$gb_username = 'root';
$gb_password = '' ;
$connection = mysqli_connect($gb_host , $gb_username , $gb_password,$gb_dbname);
$querycheck = mysqli_query($connection,"SELECT * FROM `messages` WHERE `id` = $id");
if($querycheck)
{
$message = mysqli_fetch_assoc($querycheck);
return $message;
}
else
{
mysqli_close($connection);
return NULL;
}
mysqli_close($connection);
}
why in else statment we return NULL instead of False
what's the difference between Null and False ?
The type.
False is boolean and null is a value.
So :
$test = false;
if($test === false) {
//correct
}
$test = null;
if ($test === false) {
//incorrect
} else if ($test === null) {
//correct
}
$test = false;
if(!$test) {
//correct
}
$test = null;
if(!$test) {
//correct
}
More precision in the documentation
Imho in this case and null and false are incorrect, because method should return one type of data!
In our method it should be array not special type (null) or boolean,
and it will be easy to use this method elsewhere, because everytime we know that we works with array, and we don't have write something like this:
$messages = $dao->GetMessage(27);
if (is_array($messages)) {
// ...
}
if (is_null($messages)) {
$messages = []; // because wihout it foreach will down
}
foreach ($messages as $message) {
// ...
}
And as for me it's pretty straightforward:
if we have data at db we'll receive not empty array,
if we don't have data at db - we'll receive empty array.
It's obviously!

in specific condition set and store a variable until another specific condition

Hello I'm pretty new in programming. I need to solve this problem in php but the solution in any different language will be great. I tryied to solve it with if statement but if condition is changed the variable is gone. Easy example for better understanding.
// possible conditions ( 'cond1', 'cond2', 'cond3', 'cond4','cond5' )
// conditions can be called randomly
I would like to have somethng like this:
$variable = 'off';
since ( $condition == 'cond2' )
$variable = 'on';
until ( $condition == 'cond4' )
The goal is to switch variable 'on' in the 'cond2' condition and hold it on when the others conditions are changing independently on their order until condition is changed to 'cond4' and variable is switched back to 'off'.
Thanks for any suggestions.
I don't think your current concept is realizable in PHP as you cannot listen to variables, you need to actively get notified. So one scenario with the same solution but a different concept would be
class Condition {
private $value;
private $variable = false;
public function setCondition($new_value) {
$this->value = $new_value;
}
public function getCondition() {
return $this->value;
}
public function isVariableSet() {
return ($this->variable === true); //TRUE if $this->variable is true
//FALSE otherwise
}
}
Now in the method setCondition(...) you can listen and actively set the variable.
public function setCondition($new_value) {
switch ($new_value) {
case 'cond2':
$this->variable = true;
break;
case 'cond4':
$this->variable = false;
break;
}
$this->value = $new_value;
}
With this you can use it like the following
$foo = new Condition();
$foo->setCondition('cond1');
var_dump( $foo->isVariableSet() ); //FALSE
$foo->setCondition('cond2');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond3');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond4');
var_dump( $foo->isVariableSet() ); //FALSE
Or in your case:
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
foreach ($conditions as $i => $condition) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
$results[$condition] = $toggle.' ; ';
}
If you don't create the instance of Condition outside the loop, you gain nothing as you create a new object everytime and no state stays. However, exactly that is required.
You can also do this via array_map() and save the foreach()
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
$results = array();
$setCondGetVariable = function($condition) use($cond) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
return $toggle.' ; ';
};
$results = array_map($setCondGetVariable, $conditions);

php - return variable from function

I am trying to return a variable from a function. I have the function below, which inserts a postid to the database. I need the postid's value returned to another page.
forum.php - Where the function is.
function newTopic(){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
return $postid;
}
newtopic.php - Where I need the $postid variable.
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
As you can see, I am trying to use $postid variable from the function newTopic(). Although, the $postid variable is empty.
How can I get the value from the function newTopic.php located in forum.php, to newtopic.php?
When you have used
return 100;
your code will never see
return $postid;
You can use this code to return
return array("code"=>"100","postid"=>$postid);
Now in new_topic.php use the code as shown
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic['code'])
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$newTopic['postid']");
}
Your code looks that is returning value 100 before returning $postid variable.
That's wrong.Your code will exit the function at first return.
comment the line "//return 100;"
OR return an array. You cannot return two values like u do.
Instead of doing
return 100;
return $postid;
Do
//return 100;
return array("successs"=>100,"id"=>$postid);
Then use your $newTopic variable as folows:
In switch:
switch($newTopic['success'])
Use the postId anywhere else
$newTopic['id']
try with reference like in the below code
function newTopic(&$postid){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
}
....... //some codes
$postid = null;
newTopic($postid);
$my_postId = $postid; //Now you have your post ID
OR in you exists code like
if($_POST)
{
$last_postid = null;
$newTopic = $forum->newTopic($last_postid );
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
$postid = $last_postid;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
EDIT: Call-time pass-by-reference fixed.
If you want to return two values you can not just write two returns.
There are several options to return more values. One is using an array:
return array(100, $postId);
and
list($status, $postId) = $forum->newTopic();
You can also use an associatve array as s.d suggested.
However, as your one variable only contains the status you can also use exceptions in the case the operation fails.

PHP - Validation function to return true|false, AND a message if false

I have a validation function which returns either true or false.
However, I want it to provide info as to what the problem is, when there is one.
Let's say the function is like this:
function is_valid($val) {
$result = true;
if( rule_1_not_met ) $result = false;
if( rule_2_not_met ) $result = false;
return $result;
}
Which is used like this
$val = $_GET['some_param'];
if(!is_valid($val)) $out .= 'Not so helpful feedback.';
...
I thought I could change it like this:
function is_valid($val) {
$result = array(true, array());
if( rule_1_not_met ) $result[1][] = 'Reason 1';
if( rule_2_not_met ) $result[1][] = 'Reason 2';
if(count($result[1]) > 0) $result[0] = false;
return $result;
}
And use it like this:
$val = $_GET['some_param'];
$validation_result = is_valid($val);
if(!$validation_result[0]) $out .= implode('<br/>', $validation_result[1]);
...
My question is
Am I in, for unexpected results with this?
Are there better ways to achieve this?
P.S. Would make this community wiki
You are in the right track but I would like to do this in this way
function is_valid($val,&$mes) {
$result = true;
if( rule_1_not_met ) { $mes[]='message one'; $result = false; }
if( rule_2_not_met ) { $mes[]='Message two'; $result = false; }
return $result;
}
$mes=array();
if(isvalid($val,$mes) ===false) $out .= implode('<br/>', $mes);
In my opinion, your proposed solution works fine. The only problem with it is that you have to remember that $validation_result[0] is the status and $validation_result[1] contains the messages. This might be OK with you but it will be hard to maintain if other people use your code. One thing you can do is when you call your function, you can use array destructuring to at least store the results with meaningful variable names. For example:
[$valid, $errors] = is_valid($val);
if(!$valid) $out .= implode('<br/>', $errors);
For the reason mentioned above, I like Brad Thomas's solution of creating a specialized class that contains the messages and status. Since the properties are named, you don't have to guess how to access the validation information. Also, most good IDEs will autocomplete when you try to access their properties.
I also have an alternate solution. Instead of including a boolean true or false. Just return the array of messages. The caller would just have to check if the returned array has a non-zero number of errors. Here is an example:
function get_errors($val) {
$errors = array();
if( rule_1_not_met ) $errors[] = 'Reason 1';
if( rule_2_not_met ) $errors[] = 'Reason 2';
return $errors;
}
Then the caller would use it like this:
$val = $_GET['some_param'];
$validation_result = get_errors($val);
if (count($validation_result) > 0) $out .= implode('<br/>', $validation_result);
You could use a Result object that encapsulates return data, a message and a status.
i.e.
class Result( $bResult, $sMessage, $mData ) {
public function __construct() {
$this->bResult = $bResult;
$this->sMessage = $sMessage;
$this->mData = $mData;
}
}
In Your code:
$result = new Result(true, 'some helpful message here', null);
$reasons = array();
function is_valid($val)
{
global $reasons;
if ( rule_1_not_met ) $reasons[] = 'Reason 1';
if ( rule_2_not_met ) $reasons[] = 'Reason 2';
if ( count($reasons) == 0 )
return TRUE;
else
return FALSE;
}
if (!is_valid($condition))
{
echo 'Was not valid for these reasons<br />';
foreach($reasons as $reason)
echo $reason, '<br>';
}
else
echo 'Is valid!';
This question is old, and makes a showcase of bad and outdated practices. Using global is frowned upon, and using references in this context is just the same.
Only Cave Johnson's answer makes it straight, but still the usage could be confusing. A better solution would be to write a class, but not as silly one as in the Brad Thomas's answer.
class NumberValidator
{
protected $errors;
public function validate($number)
{
if(!is_numeric($number))
{
$this->errors[] = "The value provided is not numeric";
return false;
}
if($number < 10)
{
$this->errors[] = "The number is less than 10";
return false;
}
return true;
}
public function getErrors()
{
return $this->errors;
}
}
and then it can be used like this
$validator = new NumberValidator();
if($validator->validate($number)) {
/*success*/
}
and then $validator->getErrors() can be used elsewhere

Categories