Simplified anarchy "if statement" - php

Is there a way to code this function/executable..
if($img1 > "")
{
$show = $img1;
}
elseif($img2 > "")
{
$show = $img2;
}
elseif($img3 > "")
{
$show = $img3;
}
else
{
$show = 'default.jpg';
}
echo $show;
..in a more simple way? Thx.

Any time you end up using variables named 1,2,3,etc it means you should be using an array.
If you had it like this, for example:
$img = [
1=> '',
2=> '',
3=> 'image.jpg'
];
You could then process this like so:
// Remove empty values
$img = array_filter($img);
// Echo the first value found (image.jpg)
echo current($img);
Or to add your default:
echo (count($img)) ? current($img) : 'default.jpg';
This uses a ternary operator to echo 'default.jpg' if count($img) is 0.

If you know the id number of the image, you could do something like this:
<?php
$images = array(
'myimg.jpg',
'my_awesome_img.jpg',
'awesome_awesome.jpg'
);
$show = $images[$x];
?>

You can just do
if(!empty($img1)) {
echo $img1;
} elseif(!empty($img2)) {
echo $img2;
} elseif(!empty($img3)) {
echo $img3;
} else {
echo 'default.jpg';
}
given that you only ever want to display one of these.

Did not test, but something like this:
<?php
$img1 = 'hello';
$img2 = 'world';
$array = [1,2,3];
for($i=1; $i<count($array); $i++){
$v = ${"img{$i}"};
if( !empty($v) ){
$show = $v;
break;
}
}
echo $show;
No idea what you're trying to accomplish or why the code looks like that, seems poorly constructed from the get-go.

Related

string replace without using any in-built function

With a program to replace substring in a string without using str_replace
should be generic function should work for below example:
Word : Hello world
Replace word : llo
Replace by : zz
Output should be: Hezz world
Word : Hello world
Replace word : o
Replace by : xx
Output should be: Hellxx wxxrld
This is what i wrote to solve it
function stringreplace($str, $stringtoreplace, $stringreplaceby){
$i=0;$add='';
while($str[$i] != ''){
$add .= $str[$i];
$j=0;$m=$i;$l=$i;$check=0;
if($str[$i] == $stringtoreplace[$j]){
while($stringtoreplace[$j] != ''){
if($str[$m] == $stringtoreplace[$j]){
$check++;
}
$j++;$m++;
}
if($check == strlen($stringtoreplace)){
$n=0;$sub='';
for($n=0;$n<=strlen($stringtoreplace);$n++){
$str[$l] = '';
$sub .= $str[$l];
$l++;
}
$add .= $stringreplaceby;
$i += $check;
}
}
$i++;
}//echo $add;exit;
return $add;
}
I am getting output as helzzworld .
Please take a look what I did wrong or if you have better solution for this please suggest.
You can do this by explode the main string into array then implode your stringreplaceby to your array parts creating new string
<?php
function stringreplce($str,$strreplace,$strreplaceby){
$str_array=explode($strreplace,$str);
$newstr=implode($strreplaceby,$str_array);
return $newstr;
}
echo stringreplce("Hello World","llo","zz")."<br>";
echo stringreplce("Hello World","Hel","zz")."<br>";
echo stringreplce("Hello World"," Wo","zz")."<br>";
echo stringreplce("Hello World","rl","zz")."<br>";
echo stringreplce("Hello World","ld","zz")."<br>";
?>
Try this simplest one, without using str_replace, Here we are using explode and implode and substr_count.
1. substr_count for counting and checking the existence of substring.
2. explode for exploding string into array on the basis of matched substring.
3. implode joining the string with replacement.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
if(substr_count($string, $toReplace))
{
$array=explode($toReplace,$string);
return implode($replacement, $array);
}
}
Solution 2:
Try this code snippet here not best, but working
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
while($indexArray=checkSubStringIndexes($toReplace,$string))
{
$stringArray= getChars($string);
$replaced=false;
$newString="";
foreach($stringArray as $key => $value)
{
if(!$replaced && in_array($key,$indexArray))
{
$newString=$newString.$replacement;
$replaced=true;
}
elseif(!in_array($key,$indexArray))
{
$newString=$newString.$value;
}
}
$string=$newString;
}
return $string;
}
function getLength($string)
{
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$counter++;
}
else
{
break;
}
}
return $counter;
}
function getChars($string)
{
$result=array();
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$result[]=$string[$counter];
$counter++;
}
else
{
break;
}
}
return $result;
}
function checkSubStringIndexes($toReplace,$string)
{
$counter=0;
$indexArray=array();
$newCounter=0;
$length= getLength($string);
$toReplacelength= getLength($toReplace);
$mainCharacters= getChars($string);
$toReplaceCharacters= getChars($toReplace);
for($x=0;$x<$length;$x++)
{
if($mainCharacters[$x]==$toReplaceCharacters[0])
{
for($y=0;$y<$toReplacelength;$y++)
{
if(isset($mainCharacters[$x+$y]) && $mainCharacters[$x+$y]==$toReplaceCharacters[$y])
{
$indexArray[]=$x+$y;
$newCounter++;
}
}
if($newCounter==$toReplacelength)
{
return $indexArray;
}
}
}
}
function ganti_kata($kata,$kata_awal,$kata_ganti){
$i =0; $hasil;
$panjang = strlen($kata);
while ($i < $panjang) {
if ($kata[$i] == $kata_awal) {
$hasil[$i] = $kata_ganti;
echo $hasil[$i];
}
else if ($kata[$i] !== $kata_awal){
$hasil[$i] = $kata[$i];
echo $hasil[$i];
}
$i++;
}
}
echo ganti_kata('Riowaldy Indrawan','a','x');
This code using php

dynamically name session isset how to use?

I am trying to get dynamic $_SESSION[$id] on the second page shown below, but its not working (as per the printout):
First page url
https://example.com/test.php?id=1548393
First page code
<?php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
?>
Second page url
https://example.com/test2.php?id=1548393
Second page code
<?php
session_start();
$id = $_GET['id'];
if(isset($_SESSION[$id])){
echo "working";
}else{
echo "not working";
}
?>
i found problem we can not use numeric index for $_SESSION
but we can use number in $_SESSION by convert number to roman numerals
first page url
https://example.com/test.php?id=1548393
first page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
$_SESSION[$roman_id] = "mysecretstringline";
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
second page url
https://example.com/test2.php?id=1548393
second page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
if(isset($_SESSION[$roman_id])){
echo "working";
}else{
echo "not working";
}
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
output
working
thanks #gre_gor and #Katie
Could be that in your normal code (this just looks like a quick mockup), you have a space after ?> somewhere. That could cause issues.
<?php
// start.php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
and
<?php
// next.php
session_start();
$id = $_GET['id'];
if (isset($_SESSION[$id])) {
echo "working";
} else {
echo "not working";
}
works for me. Notice no ?> characters.
UPDATE:
The following might be of interest regarding session name constraints (can a php $_SESSION variable have numeric id thus : $_SESSION['1234’])
You have that issue in your example you could just add an id_ and then do the same check when validating/getting the session.

check my links format with php

I have something like this :
<?php
$siteurl = "http://www.example.com/";
$pageid = "ed2689";
$pageurl = $siteurl.$pageid;
?>
and the links will be like this:
http://www.example.com/ed2689
http://www.example.com/report/ed2689
I have used preg_match to check the format for each one of this links
for the first link, it must be exactly like this:
$siteurl.[a-z0-9]
and i have used this :
if (preg_match('/[$siteurl]+[a-z0-9]/', $pageurl) && !preg_match('/[=]|[?]/', $pageurl))
{
echo 'Ok',
}
and for for the second link, it must be exactly like this:
$siteurl.'report/'.[a-z0-9]
and i have used this :
if (preg_match('/[$siteurl]+[report]+[a-z0-9]/', $req_uri) && !preg_match('/[=]|[?]/', $req_uri))
{
echo 'Ok',
}
and it doesn't work correctly..any help please ?
Thanks.
Let me know if not works
<?php
$siteurl = 'http://www.example.com/report/ed2689';
//$siteurl = 'http://www.example.com/ed2689';
if(strpos($siteurl,'www.example.com') === false) echo 'not my site';
else {
$arr = explode('www.example.com/',$siteurl);
$suburl = trim($arr[1]);
if (preg_match('/^[a-z0-9]+$/', $suburl) || preg_match('/^report\/[a-z0-9]+$/', $suburl))
{
echo 'ok';
}
}
?>

if else simple beginner issue

Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}

Generating XML file through PHP results in a minor issue . Please help

In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.

Categories