PHP shorthand if echo else assign variable - php

I want to write this in one line if possible:
if ($some_var === true) {
$return .= $input;
} else {
echo $input;
}
Obviously I don't want this:
if ($some_var === true) { $return .= $input; } else { echo $input; }
but a shorter version of it.
I looked at other answers but I only find the echo (expression) ? true : false; statements. I don't want to echo on the true, only on the false.

$some_var = true;
$input = 'abc';
$return = '123';
echo ($some_var === true) ? ($return .= $input) : ($input);

Related

How to extract the body part of a function?

The function extractBody() extracts the body part of a function:
$data = '
<?php
function my_function($param){
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
}
?>
';
function extractBody($functionName, $data) {
$c = preg_match_all("/function\s+".$functionName."\s*\((?<param>[^\)]*)\)\s*(?<body>\{(?:[^{}]+|(?&body))*\})/", $data, $matches);
return $c > 0 ? $matches['body'] : null;
}
$body =extractBody("my_function", $data);
var_dump($body);
result: The variable $body contains
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
Now I need a second function to work with lambda functions (function is assigned to a variable)
$data2 = '
<?php
$my_function = function($param){
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
}
?>
';
function extractBody2($functionName, $data) {
$c = preg_match_all("/".$functionName."\s+=\s+function\s+\s*\((?<param>[^\)]*)\)\s*(?<body>\{(?:[^{}]+|(?&body))*\})/", $data, $matches);
return $c > 0 ? $matches['body'] : null;
}
$body2 =extractBody2("my_function", $data2);
var_dump($body2);
Unfortunately, I'm not a regex specialist and I get NULL back.
I think the error must be somewhere here: "/".$functionName."\s+=\s+
regex101 didn't reveal any issues though.
This works for me:
function extractBody2($functionName, $data) {
$c = preg_match_all("/\\$".$functionName."\s+=\s+function\s*\((?<param>[^\)]*)\)\s*(?<body>\{(?:[^{}]+|(?&body))*\})/", $data, $matches);
return $c > 0 ? $matches['body'] : null;
}

How to repeat the same action for diffrent variables

<!-- language: php -->
<?php
// test variables
$l1 = "http://youtube.com/channel/";
$l2 = "http://youtube.com/channel/";
$l3 = "http://youtube.com/channel/";
$l4 = "http://youtube.com/channel/";
$fl = "http://youtube.com/channel/";
//set error false as default
$error = "false";
//check if variables are ready for use, if they are, add them to `$l` array
//I do each check as a seperate line, as it looks cleaner than 1 long if statement.
$l = [];
if(!empty($l1)) $l[] = $l1;
if(!empty($l2)) $l[] = $l2;
if(!empty($l3)) $l[] = $l3;
if(!empty($l4)) $l[] = $l4;
if(!empty($fl)) $l[] = $fl;
foreach($l as $key => $value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($l, $searchUrl) !== false && strpos($l, $search) === false) {
$l = $value."".$search;
}
if($error == "false") {
echo $l1;
echo $l2;
echo $l3;
echo $l4;
echo $fl;
}
// deliver the error message
//Check if $error has been set to true at any point
if($error == "true") {
//loop through error array, echo error message if $errorNumber matches.
//at this point we KNOW there was an error at some point, no need to use a switch really
foreach($errors as $errorNumber) {
echo "Something went wrong here $errorNumber :o";
}
}
?>
Hello, my problem is at the end of the code where the strpos function is, so basically I want to check every url, once if it contains a certain url, and then add something to the end if it is so. But I don't want to repeat an if statement 4 times($fl variable doesn't has to be checked), I am quite new in all that so I hope somebody can help me, I tought about a switch statement but I guess there is a better way. And if I put it in the foreach aboth, it doesn't applies on the certain variables, only on the value variable.
You can assign $value by reference using this foreach header (notice the & in front of $value):
foreach($l as $key => &$value) {
By doing this every change you do to $value will also be done to the corresponding value in the $l array.
Then at the end of the foreach loop you put this code:
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
So your final foreach loop should look like this:
foreach($l as $key => &$value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
}
You can read more about using references in foreach loops here: PHP: foreach
Edit:
To apply the changes not only to the elements of the $l array, but also to the original variables $l1, $l2 and so on, you should assign the elements to your array as references too:
$l = [];
if(!empty($l1)) $l[] = &$l1;
if(!empty($l2)) $l[] = &$l2;
if(!empty($l3)) $l[] = &$l3;
if(!empty($l4)) $l[] = &$l4;
if(!empty($fl)) $l[] = &$fl;
Personally, I think this is a good candidate for moving to a class. To be honest I'm not 100% sure what you are doing but will try to convert your code to a class.
class L {
public $raw = null;
public $modified = null;
public $error = false;
// create the class
public function __construct($data=null) {
$this->raw = $data;
// Check the raw passed in data
if ($data) {
$this->isUrl();
}
// If there was no error, check the data
if (! $this->error) {
$this->search();
}
}
// Do something ?
public function debug() {
echo '<pre>';
var_dump($this);
echo '</pre>';
}
public function getData() {
return ($this->modified) ? : $this->raw;
}
private function isUrl() {
$this->error = (! preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $this->raw));
}
// Should a failed search also be an error?
private function search() {
if ($this->raw) {
if ( (strpos($this->raw, "youtube.com/channel") !== false) &&
(strpos($this->raw, "?sub_confirmation=1") === false) ) {
$this->modified = $this->raw ."?sub_confirmation=1";
}
}
}
}
// Test data
$testList[] = "test fail";
$testList[] = "https://youtube.com/searchFail";
$testList[] = "https://youtube.com/channel/success";
$testList[] = "https://youtube.com/channel/confirmed?sub_confirmation=1";
// Testing code
foreach($testList as $key=>$val) {
$l[] = new L($val);
}
foreach($l as $key=>$val) {
// Check for an error
if ($val->error) {
$val->debug();
} else {
echo '<pre>'.$val->getData().'</pre>';
}
}
And the output would be:
object(L)#1 (3) {
["raw"]=>
string(9) "test fail"
["modified"]=>
NULL
["error"]=>
bool(true)
}
https://youtube.com/searchFail
https://youtube.com/channel/success?sub_confirmation=1
https://youtube.com/channel/confirmed?sub_confirmation=1

big IF function not working in PHP?

Dears,
I am surprised why the PHP 'IF ELSE' function is not working properly. I guess it's a bit long but I made Algorithm for it and logically it would work perfectly. Can anyone have any clue why the function not working properly . please ..
<?php
//entry Marks
$tc=80;$tf=33;$pc=null;$pf=50;
if($tc!=NULL && $tf!=NULL && $pc!=NULL && $pf!=NULL){
echo $tc." ".$tf." ".$pc." ".$pf;
}else{
if($tc!=NULL){
if($tf!=NULL && $pc!=NULL && $pf!=NULL){
echo "tf.pc.pf";
}else{
if($tf!=NULL){
if($pc!=NULL && $pf!=NULL){
echo "tf.pc.pf";
}else{
if($pc!=NULL){
if($pf!=NULL){
echo "tf.pc.pf";
}else{
echo "tf.pc";
}
}else{
if($pf!=NULL){
echo "tf.pf";
}else{
echo "tf";
}
}
}
}else{
if($pc!==NULL && $pf!=NULL){
echo "pc.pf";
}else{
if($pc!=NULL){
if($pf!=NULL){
echo "pc.pf";
}else{
echo "pc";
}
}else{
if($pf!=NULL){
echo "pf";
}else{
echo "null";
}
}
}
}
}
}else{ //2nd part
if($tf!=NULL && $pc!=NULL && $pf!=NULL){
echo "tf.pc.pf";
}else{
if($tf!=NULL){
if($pc!=NULL && $pf!=NULL){
echo "tf.pc.pf";
}else{
if($pc!=NULL){
if($pf!=NULL){
echo "tf.pc.pf";
}else{
echo "tf.pc";
}
}else{
echo "tf";
}
}
}else{
if($pc!=NULL && $pf!=NULL){
echo "pc.pf";
}else{
if($pc!=NULL){
if($pf!=NULL){
echo "pc.pf";
}else{
echo "pc";
}
}else{
if($pf!=NULL){
echo "pf";
}else{
echo "null";
}
}
}
}
}
}
}
?>
Your code is really difficult to follow, this code sample below shows a simplified version which appends to a string the values or text depending on if the variable is NULL or not. You can change what the if-else statements add to the result string easily. At the end I remove the "." at the end of the final string.
$result = "";
if($tc == NULL){
$result .= "tc.";
}else{
$result .= $tc.".";
}
if($tf == NULL){
$result .= "tf.";
}else{
$result .= $tf.".";
}
if($pc == NULL){
$result .= "pc.";
}else{
$result .= $pc.".";
}
if($pf == NULL){
$result .= "pf.";
}else{
$result .= $pf.".";
}
$output = rtrim($result, '.');
echo $output;
I will update my answer when its a bit clearer what output you are after
As noted in the other answer, your code is much longer than needed. This length makes it hard to follow. You could use a foreach loop to go through all your columns (which will make adding columns much easier).
Assuming I understand what you are looking for, you could use something like:
$tc=80;$tf=33;$pc=null;$pf=50;
$columns = array('tc'=>$tc,'tf'=>$tf,'pc'=>$pc,'pf'=>$pf);
$i = 0;
$output = "";
foreach ($columns as $key=> $column) {
if (!$column == null) {
$output .= $key.".";
}
}
// strip last period:
$output = rtrim($output, '.');
echo $output;
Link to php sandbox for demo here.
I do not have the answer of why your large if-statement do not work. But I do have a suggestion of making a PHP function to handle your specific need:
function check($tc=null,$tf=null,$pc=null,$pf=null){
$r = array();
if($tc != null){ $r[] = 'tc'; }
if($tf != null){ $r[] = 'tf'; }
if($pc != null){ $r[] = 'pc'; }
if($pf != null){ $r[] = 'pf'; }
if(empty($r)){
return 'null';
} else {
return implode('.', $r);// MAKE STRING OF ARRAY
}
}
And call the function like this:
$tc=80;$tf=33;$pc=null;$pf=50;
echo check($tc, $tf, $pc, $pf);
Try it out: https://eval.in/735202

checking zero is null or not in php

i am working on validation and comparisons!! i have a field that can contain the value $val=0 or $val="some-value" or $val="" or $val=0 basically i want the $val="0"or $val=0 to be validated as true..
if($val){
//works for $val="some-value"
//doesnot work for $val=0 or $val="0";
} else
{
//works corrent for $val=""
}
one conditional approach i used is
$val="";
if($val || $val==0){
echo "true";
}
else
{
//should be false but it is true
echo "false";
}
did you try this?
$val = "";
if ($val == '0') {
echo "TRUE";
# code...
}
elseif ($val == "") {
echo "FALSE";
}
There is a useful php native function is_null
if (is_null($val) || $val === "") {
//invalid
} else {
//valid
}
You can use PHP integer casting & can do it like this:
if ((int) $val === 0) {
return true;
} else {
return false;
}
Hope this helps!

Using PHP write an anagram function?

Using PHP write an anagram function? It should be handling different phrases and return boolean result.
Usage:
$pharse1 = 'ball';
$pharse2 = 'lbal';
if(is_anagram($pharse1,$pharse2)){
echo $pharse1 .' & '. $pharse2 . ' are anagram';
}else{
echo $pharse1 .' & '. $pharse2 . ' not anagram';
}
There's simpler way
function is_anagram($a, $b) {
return(count_chars($a, 1) == count_chars($b, 1));
}
example:
$a = 'argentino';
$b = 'ignorante';
echo is_anagram($a,$b); // output: 1
$a = 'batman';
$b = 'barman';
echo is_anagram($a,$b); // output (empty):
function is_anagram($pharse1,$pharse2){
$status = false;
if($pharse1 && $pharse2){
$pharse1=strtolower(str_replace(" ","", $pharse1));
$pharse2=strtolower(str_replace(" ","", $pharse2));
$pharse1 = str_split($pharse1);
$pharse2 = str_split($pharse2);
sort($pharse1);
sort($pharse2);
if($pharse1 === $pharse2){
$status = true;
}
}
return $status;
}
function check_anagram($str1, $str2) {
if (count_chars($str1, 1) == count_chars($str2, 1)) {
return "This '" . $str1 . "', '" . $str2 . "' are Anagram";
}
else {
return "This two strings are not anagram";
}
}
ECHO check_anagram('education', 'ducatione');
I don't see any answers which have addressed the fact that capital letters are different characters than lowercase to count_chars()
if (isAnagram('Polo','pool')) {
print "Is anagram";
} else {
print "This is not an anagram";
}
function isAnagram($string1, $string2)
{
// quick check, eliminate obvious mismatches quickly
if (strlen($string1) != strlen($string2)) {
return false;
}
// Handle uppercase to lowercase comparisons
$array1 = count_chars(strtolower($string1));
$array2 = count_chars(strtolower($string2));
// Check if
if (!empty(array_diff_assoc($array2, $array1))) {
return false;
}
if (!empty(array_diff_assoc($array1, $array2))) {
return false;
}
return true;
}
here is my variant :
public function is_anagram($wrd_1, $wrd_2)
{
$wrd_1 = str_split ( strtolower ( utf8_encode($wrd_1) ) );
$wrd_2 = str_split( strtolower ( utf8_encode($wrd_2) ) );
if ( count($wrd_1)!= count($wrd_2) ) return false;
if ( count( array_diff ( $wrd_1 ,$wrd_2) ) > 0 ) return false;
return true;
}
Heheh little large but work as well :)
public static function areStringsAnagrams($a, $b)
{
//throw new Exception('Waiting to be implemented.');
$a = str_split($a);
$test = array();
$compare = array();
foreach ($a as $key) {
if (!in_array($key, $test)) {
array_push($test, $key);
$compare[$key] = 1;
} else {
$compare[$key] += 1;
}
}
foreach ($compare as $key => $value) {
if ($value !== substr_count($b, $key)) {
return false;
}
}
return true;
}

Categories