<?php
$one = "A";
$two = "f";
$three = "";
$four = "d";
$output = "";
$output = $one.",".$two.",".$three.",".$four;
if ($four == "") {
echo $output;
}
elseif ($three == "") {
echo $output;
}
elseif ($two == "") {
echo $output;
}
elseif ($one == "") {
echo $output;
}
?>
Hi, the output of the above program gives me as A,f,,d now i don't want the empty space between two values if i omit any one of them,can any one please tell me how to do that.
Please note that i need to use only if-else statements and no loops can be used.
Thank you.
Can you use arrays? You could do something like
$output = implode(',', array_filter(array($one, $two, $three, $four)));
<?php
$one = "A";
$two = "f";
$three = "";
$four = "d";
$output = "";
if($output && $one){
$output .= ",".$one;
}else{
$output .= $one;
}
if($output && $two){
$output .= ",".$two;
}else{
$output .= $two;
}
if($output && $three){
$output .= ",".$three;
}else{
$output .= $three;
}
if($output && $four){
$output .= ",".$four;
}else{
$output .= $four;
}
echo $output;
?>
check here : https://eval.in/540856
Related
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
i'm writing a php web script with mvc, but i'm concerned about code is safe.
i fear most "eval($str)", but i try a lot of php function string but nothing happened.
$a = func_get_args();
if((func_num_args()-1)%2 == 0){
$str = "";
array_shift($a);
for($i = 0;$i<sizeof($a);$i++){
if($i%2==0){
if(!is_numeric($a[$i])){
if($a[$i] == 'filter'){
$filter=1;
}
$str.= "$".stripslashes($a[$i])." = ";
}else{
$str.= 'page';
}
}else{
if($filter != 1){
if(is_numeric($a[$i])){
$str.= stripslashes($a[$i]).";";
}else{
$str.=1;
}
}else{
$arr = explode("-",$a[$i]);
$dizz = 'array(';
for($j=0;$j<sizeof($arr);$j++){
if(($j%2)==0){
$dizz .= '\''.stripslashes($arr[$j]).'\'=>';
}else{
$dizz .= '\''.stripslashes($arr[$j]).'\',';
}
}
$dizz = rtrim($dizz,',');
$dizz .= ');';
$str.= $dizz;
}
}
}
eval($str);
}
$filter = isset($filter) ? $filter : false;
$page= isset($page) ? $page: '';
$count= isset($count) ? $count: '';
if($count == ''){
switch ($process) {
case 'table':
$count = 40;
break;
case 'detailed':
$count = 3;
break;
case 'mobile':
$count = 12;
break;
default:
$count = '';
break;
}
}
if($count != ''){
if(is_numeric($count )){
if($count <=200 && $count >0){
$count = $count ;
}else{
$count = 40;
}
}else{
$count = 1;
}
}
if(!is_numeric($page)){
$page= 1;
}
to sql query->
$new_filter = "Where ";
if($filter){
foreach ($filteras $key => $value) {
$new_filter .= 'k.'.$key.'='.$value.' and ';
}
$new_filter = rtrim($new_filter,' and ');
$filter= $new_filter;
}else{
$filter= '';
}
$limit = ($limit) ? 'LIMIT 30' : '';
if($id == ''){
$where = $filter;
}else{
$where = $id;
}
$query = 'select * from kullanici as k join kisiler as ki on k.id = ki.kullanici_id join iletisim as i on k.id = i.kullanici_id '.$where.' '.$siralama.' '.$limit;
$query = $this->_db->prepare($query);
$query->execute();
example url:
profile/show/mobile/page/4/count/5/filter/echo-"'xzcxza'"-sadas-asdxc
this results:
$page = 4;$count= 5;$filter= array('echo'=>'%22%27xzcxza%27%22','sadas'=>'asdxc');
Here is python code:
def is_palindrome(s):
return revers(s) == s
def revers(s):
ret = ''
for ch in s:
ret = ch + ret
return ret
print is_palindrome('RACECAR')
# that will print true
when i convert that function to php.
function is_palindrome($string){
if (strrev($string) == $string) return true;
return false;
}
$word = "RACECAR";
var_dump(is_palindrome($word));
// true
Both functions works fine but, how can i revers string with php in loop ??
$string = str_split(hello);
$output = '';
foreach($string as $c){
$output .= $c;
}
print $output;
// output
hello
//i did this,
that's work find but is there any way to do that in better way ?
$string = "hello";
$lent = strlen($string);
$ret = '';
for($i = $lent; ($i > 0) or ($i == 0); $i--)
{
$ret .= $string[$i];
#$lent = $lent - 1;
}
print $output;
//output
olleh
Replace
$output .= $c;
with
$output = $c . $output;
Can't be shorter I guess. With a loop :)
$word = "Hello";
$result = '';
foreach($word as $letter)
$result = $letter . $result;
echo $result;
I don't try that code, but I think that it should work:
$string = "hello";
$output = "";
$arr = array_reverse(str_split($string)); // Transform "" to [] and then reverse => ["o","l","l,"e","h"]
foreach($arr as $char) {
$output .= $char;
}
echo $output;
Another way:
$string = "hello";
$output = "";
for($i = strlen($string); $i >= 0; $i--) {
$output .= substr($string, $i, 1);
}
echo $output;
strrev() is a function that reverses a string in PHP.
http://php.net/manual/en/function.strrev.php
$s = "foobar";
echo strrev($s); //raboof
If you want to check if a word is a palindrome:
function is_palindrome($word){ return strrev($word) == $word }
$s = "RACECAR";
echo $s." is ".((is_palindrome($s))?"":"NOT ")."a palindrome";
How increase the performance of this code in php?
or any alternative method to find out the comment if the string starts with # then call at()
or if string starts with "#" then call hash()
here the sample comment is "#hash #at #####tag";
/
/this is the comment with mention,tag
function getCommentWithLinks($comment="#name #tag ###nam1 test", $pid, $img='', $savedid='', $source='', $post_facebook='', $fbCmntInfo='') {
//assign to facebook facebookComment bcz it is used to post into the fb wall
$this->facebookComment = $comment;
//split the comment based on the space
$comment = explode(" ", $comment);
//get the lenght of the splitted array
$cmnt_length = count($comment);
$store_cmnt = $tagid = '';
$this->img = $img;
$this->saveid = $savedid;//this is uspid in product saved table primary key
//$this->params = "&product=".base_url()."product/".$this->saveid;
$this->params['product'] = base_url()."product/".$this->saveid;
//$this->params['tags']='';
foreach($comment as $word) {
//check it is tag or not
//the first character must be a # and remaining all alphanumeric if any # or # is exist then it is comment
//find the length of the tag #mention
$len = strlen($word);
$cmt = $c = $tag_name = '';
$j = 0;
$istag = false;
for($i=0; $i<$len; $i++) {
$j = $i-1;
//check if the starting letter is # or not
if($word[$i] == '#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_tag($tag_name, $pid);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
//append to the store_coment if the i is 1 or -1 or $word[j]!=#
$this->store_cmnt .= $word[$i];//23,#
}
}else if($word[$i]=='#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_mention($tag_name, $pid, $fbCmntInfo);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
$this->store_cmnt .= $word[$i];//23,#
}
}else if( $this->alphas($word[$i]) && $i!=0){
if($tag_name=='') {
//check the length of the string
$strln=strlen($this->store_cmnt);//4
if($strln != 0) {
$c = substr($this->store_cmnt, $strln-1, $strln);//#
if($c=='#' || $c=='#') {
$this->store_cmnt = substr($this->store_cmnt, 0, $strln-1);//23,
$tag_name = $c;
}
}
//$tag_name='';
}
//check that previous is # or # other wise it is
if($c=='#' || $c=='#') {
$tag_name .= $word[$i];
$istag = true;
//check if lenis == i then add anchor tag her
if($i == $len-1) {
$istag =false;
//check if it is # or #
if($c=='#')
$this->save_tag($tag_name,$pid);
else
$this->save_mention($tag_name,$pid,$fbCmntInfo);
//$this->store_cmnt .= '<a >'. $tag_name.'</a>';
}
}else{
$this->store_cmnt .= $word[$i];
}
}else{
if($istag) {
//insert $tag_name
$this->save_tag($tag_name,$pid);
$istag = false;
$tag_name = '';
}
$this->store_cmnt .= $word[$i];
}
}
$this->store_cmnt .=" ";
}
}
Try This it may be help full
function getResultStr($data, $param1, $param2){
return $param1 != $param2?(''.$data.''):$data;
}
function parseWord($word, $symbols){
$result = $word;
$status = FALSE;
foreach($symbols as $symbol){
if(($pos = strpos($word, $symbol)) !== FALSE){
$status = TRUE;
break;
}
}
if($status){
$temp = $symFlag = '';
$result = '';
foreach(str_split($word) as $char){
//Checking whether chars are symbols(#,#)
if(in_array($char, $symbols)){
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
}
$symFlag = $temp = $char;
} else if(ctype_alnum($char) or $char == '_'){
//accepts[0-9][A-Z][a-z] and unserscore (_)
//Checking whether Symbol already started
if($symFlag != ''){
$temp .= $char;
} else {
//Just appending the char to $result
$result .= $char;
}
} else {
//accepts all special symbols excepts #,# and _
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
$temp = $symFlag = '';
}
$result .= $char;
}
}
$result .= getResultStr($temp, $symFlag, '');
}
return $result;
}
function parseComment($comment){
$str = '';
$symbols = array('#', '#');
foreach(explode(' ', $comment) as $word){
$result = parseWord($word, $symbols);
$str .= $result.' ';
}
return $str;
}
$str = "#Richard, #McClintock, a Latin professor at $%#Hampden_Sydney #College-in #Virginia, looked up one of the ######more obscure Latin words, #######%%#%##consectetur, from a Lorem Ipsum passage, and #going#through the cites of the word in classical literature";
echo "<br />Before Parsing : <br />".$str;
echo "<br /><br />After Parsing : <br />".parseComment($str);
use strpos or preg_match or strstr
Please refer string functions in php. You can do it in a line or two with that in built functions.
If it not matches better to write a regex.
can someone help with this?
I need the following function to do this...
$x = 'AAAABAA';
$x2 = 'ABBBAA';
function foo($str){
//do something here....
return $str;
}
$x3 = foo($x); //output: A4B1A2
$x4 = foo($x2);//output: A1B3A2
substr_count is your friend
or rather this
function foo($str) {
$out = '';
preg_match_all('~(.)\1*~', $str, $m, PREG_SET_ORDER);
foreach($m as $p) $out .= $p[1] . strlen($p[0]);
return $out;
}
function foo($str) {
$s = str_split($str);
if (sizeof($s) > 0) {
$current = $s[0];
$output = $current;
$count = 0;
foreach ($s as $char) {
if ($char != $current ) {
$output .= $count;
$current = $char;
$output .= $current;
$count = 1;
}
else {
$count++;
}
}
$output .= $count;
return $output;
}
else
return "";
}