PHP - Variable Safe Output [duplicate] - php

This question already has answers here:
Is there a better PHP way for getting default value by key from array (dictionary)?
(8 answers)
Closed 3 years ago.
I'm fetching information from a unofficial API. This API is very large and sometimes doesn't have all elements in it. I'm trying to display values from this API on my site without any errors.
What I've done is check the JSON values like so, to prevent errors:
echo (isset($json['item'])) ? $json['item'] : '';
Works, but it looks very unorganized. I've thought about creating a function to handle safe output, like so:
public function safeoutput($input, $fallback = '') {
if(isset($input)) {
return $input;
}
if(empty($input) || !isset($input)) {
return $fallback;
}
}
and then doing:
echo $engine->safeoutput($json['item'], 'Unavailable');
That unfortuanlly still outputs the Undefined variable error.
I was wondering if there's a better way to handle such information like I showed in the example.

Problem is that the key might not be set, so you would have to check it:
public function safeoutput($input, $key, $fallback = '') {
if(isset($input[$key])) {
return $input;
}
if(empty($input[$key]) || !isset($input[$key])) {
return $fallback;
}
}
Or you can have a shorter version:
public function safeoutput($input, $key, $fallback = '') {
if(array_key_exists($key, $input) && !empty($input[$key])){
return $input[$key];
}
return $fallback;
}
And call the method with the array and the key:
echo $engine->safeoutput($json, 'item', 'Unavailable');

Related

Recursive Function returns null value [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
Below recursive function i am trying to get array of codes. For example input 'bme4', output should be like [0]=>'bme'[1]=>'bm'[2]=>'b'. But the return value is null eventhough i can get the correct return value with var_dump().
function get_parent_cat_code($code, $category_codes) {
$parent_cat_code = substr($code, 0, -1);
if ($parent_cat_code != ''){
$category_codes[] = $parent_cat_code;
get_parent_cat_code($parent_cat_code, $category_codes);
} else {
var_dump($category_codes);
return $category_codes;
}
}
Solved!
function get_parent_cat_code($code,$category_codes){
$parent_cat_code=substr($code, 0, -1);
if($parent_cat_code!=''){
$category_codes[]=$parent_cat_code;
return get_parent_cat_code($parent_cat_code,$category_codes); //i used return for calling recursive function.
}else{
var_dump($category_codes);
return $category_codes;
}
}

Class to check empty inputs validation with php OOP [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 3 years ago.
I dont understand why this is not working and any advice for oop im beginner on oop paradigm
My class
class formvalidation {
public function check_empty_input($inputs=[]){
$checked = false;
foreach($inputs as $valor){
if(empty($valor)){
$checked = false;
break;
} else {
$checked = true;
}
}
if($checked = true){return true;}
else {return false;}
}
}
Check if posts are empty
$formvalidation= new formvalidation();
$inputs = array($_POST['name'],$_POST['email'],$_POST['pass'],$_POST['confirmpass']);
if($formvalidation->check_empty_input($inputs))
Well, the problem is in the return if, you are using = as comparison operator, where instead you should have used ==, and so the function will return always true... also you should use a static function from the moment that you don't need a object to invoke this function, try with this one:
<?php
class formvalidation {
public static function check_empty_input($inputs = []) : bool {
$everything_filled = true; //start with this supposition
foreach ($inputs as $valor) {
if (empty($valor)) {
$everything_filled = false; // is something is empty, than the supposition is false
break;
}
}
return $everything_filled; // return the supposition result value
}
}
$is_my_inputs_filled = formvalidation::check_empty_inputs([
$_POST['name'],
$_POST['email'],
$_POST['pass'],
$_POST['confirmpass'],
]);
If it doesn't work, please explain better what you mean with "doesn't work"

Check multiple variables at once in PHP using IF [duplicate]

This question already has answers here:
Using if(!empty) with multiple variables not in an array
(15 answers)
Closed 3 years ago.
With these variables:
$var1='a';
$var2='b';
How can I check if they are both empty at once without the need of doing this:
if(empty($var1) && empty($var2)){
}
or
if($var1=='' && $var==''){
}
I mean something like:
if(($var1 && $var)==''){
}
Depending on your scale requirements and how large the data you'll be storing in these vars is, you could just do a straight concatenation:
if($var1 . $var2 == '') {
// blank strings in both
}
Alternatively, using empty():
if(empty($var1 . $var2)) {
// blank strings in both
}
Repl.it
How about a utility function:
function is_any_empty() {
$args = func_get_args();
foreach($args as $arg) {
if(empty($arg)) return true;
}
return false;
}
var_dump(is_any_empty("")); // bool(true)
var_dump(is_any_empty("ds", "")); // bool(true)
var_dump(is_any_empty("ds", "dd")); // bool(false)
I mean, that's kinda how you do it. But if you want to ensure that they both are not empty, you'd probably want your if statement to look more like this:
if(!empty($var1) && !empty($var2)) {
// Do stuff! They both exist!
}
I'd prefer an empty check because if $var1 and $var2 haven't been defined, you'll get notices all over your error logs.
Hope that helps!

How do I extract the parameters in a function call from source code? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
PHP: Get name of variable passed as argument
How to get a variable name as a string in PHP?
If I have
$abc = '123';
function write($var){
}
How would I inside write find out that the variable now represented by $var was called $abc?
It's not possible. Even pass-by-reference won't help you. You'll have to pass the name as a second argument.
But what you have asked is most assuredly not a good solution to your problem.
You can not get the variable name, but if you want it for debugging, then you can use PHP's built-in debug_backtrace(), and I recommend to take a look on Xdebug as well.
With this function, you can get some data on the caller, including the file and line number, so you can look up that line manualy after running the script:
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
Full example:
<?php
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
function write($var)
{
var_dump(debug_caller_data());
}
function caller_function()
{
$abc = '123';
write($abc);
}
$abc = '123';
write($abc);
caller_function();

return an array from a recursive function [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I think I need some explanations about the recursivity... I looked at some same issues over forums but it didn't help me a lot.
Here is my function :
public function tas ($nb_gift, array $winners)
{
if ( !empty( $nb_gift ) ){
$id_winner = rand( 10, 15 );
if ( !$this->_in_array_r($id_winner, $winners) ){
$existing_user = $this->getWinner( $id_winner );
}
if( !empty( $existing_user ) && $nb_gift > 0 ){
$winners[] = array( $existing_user, 'iphone5');
$this->tas($nb_gift - 1, $winners);
}
else {
if($nb_gift > 0)
{
$this->tas($nb_gift, $winners);
}
}
}
else {
//print_r($winners);
return $winners;
}
}
At the end I have an array composed of the winners. Even if the print_r works, the return doesn't give me back my array.
Does the function need some optimisation ?
You are never returning anything from the first if branch. If you call tas() initially and it goes into the first if branch, it never returns, hence the caller is never getting anything back.
Recursion is nothing special, really. You call a function, you get a result:
$winners = tas();
Simple. Internally that functions may call other functions:
function tas() {
return foo();
}
There's no restriction that tas can't call itself, but it's still bound by the same rules of returned data:
function tas() {
if (...) {
foo(); // <-- doesn't return anything
} else {
return foo();
}
}
Just substitute foo() in the above example by tas() for the same concept, but including recursion.

Categories