I'm outputting a custom user field in Wordpress, which is user's Twitter username. Some users might add it with '#' symbol, some might without. How can I output that field and check if the symbol already exists, if not, add it?
This is code I'm using to output usrename:
<?php echo get_the_author_meta('twitter_name'); ?>
<?php
$authorMeta = get_the_author_meta('twitter_name');
if (strpos('#', $authorMeta) !== 0) {
$authorMeta = '#'.$authorMeta;
}
echo $authorMeta;
you need to check if # is on 1st place, you can do this in many ways
<?php
$authorMeta = get_the_author_meta('twitter_name');
if ($authoMeta[0] != '#') {
$authorMeta = '#'.$authorMeta;
}
echo $authorMeta;
Try this...it might help
$a = get_the_author_meta('twitter_name');
$b = explode('#',$a);
if($b[1] == 0){
echo "#".$a;
}
else{
echo $a;
}
Related
Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php
I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>
I want to have if the variable = null then he makes it to 1.
if the variable exist do nothing and dont make it again to 1.
i got this code:
if (isset($_POST["register"])) {
if(!$l_NextPage){
$l_NextPage = 1;
echo "helaas" . "</br>";
}
if($l_NextPage == 1){
echo "hoi";
$l_NextPage = 2;
}else if($l_NextPage == 2){
echo "doei";
}
}
only the code dont work i tried empty, isset, $var == FALSE but everytime he makes $l_NextPage to 1. is there any solution i tried this too with session but even it don't work!
What am I doing wrong?
what happen when you refresh page, it assign $l_NextPage = 1 every time, thats why all the time hoi printed
you can use sessions for preserving value of variable after page refresh
try this code
// write this line of code at top of php block
session_start();
if (isset($_POST["register"]))
{
if (!isset($_SESSION["l_NextPage"]))
{
$_SESSION["l_NextPage"] = 1;
echo "helaas" . "</br>";
}
if($_SESSION["l_NextPage"] == 1)
{
echo "hoi";
$_SESSION["l_NextPage"] = 2;
}
else if($_SESSION["l_NextPage"] == 2)
{
echo "doei";
//unset( $_SESSION['l_NextPage'] ); unset varibale
}
}
after reaching at prefixed condition you can unset varible using
unset( $_SESSION['l_NextPage'] );
i have not tested code but this should work
you should try:
if(!isset($l_NextPage)) {
$l_NextPage = 1;
echo "helaas" . "</br>";
}
elseif($l_NextPage == 1) {
(...)
try like this,
if(!empty(trim($l_NextPage)))
I have this code:
<?php $url = JURI::getInstance()->toString();
if ($url == "http://example.com/news/latest/"){
echo "This is latest page";
} else {
echo "This is not latest page";
}
?>
What I'm trying to do is instead of 'http://example.com/news/latest/', how can I select the pages/items under /latest/. If it makes any more sense, here's a syntax:
if ($url == "http://example.com/news/latest/" + ANYTHING UNDER THIS)
I cannot use not equal to ($url !=) since it will include other parent pages not equal to /latest/. I just want what's under it. If anyone understands it, I need help on how to put it into code.
Update:
What I'm trying to do is if the page is example.com/news/latest, it will echo "Latest". And if for example, I am in example.com/news/latest/subpage1/subpage2, it will echo "You are in a page that is under Latest." Anything beyond "Latest" will echo that.
$str = 'example.com/news/latest/dfg';
preg_match('/example.com\/news\/([^\/]+)\/?(.*)/', $str, $page);
if(isset($page[2]) && $page[2])
echo 'You are under: ' , $page[1];
elseif(isset($page[1]))
echo 'At: ' , $page[1];
else
echo 'Error';
Edit: after clarification switched to regular expression.
Use a regular expression:
$matches = array();
if((preg_match('#http://example\.com/news/latest/(.*)#', $url, $matches)) === 1) {
if(strlen($matches[0]) > 0) {
echo "You're at page: $matches[0]";
} else {
echo "You're at the root";
}
} else {
// Error, incorrect URL (should not happen)
}
EDIT: Fixed, untested so you may have to tweak it a little
Having one of those brain fade moments this morning. I have the following php:
$imgset = $result->fields[6];
if ($imgset = '')
{
$imgset = 'logo';
}
else
{
$imgset = $result->fields[6];
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
Where it looks to see if the result from the database is blank and if so, should put in logo.jpg instead of whatever the result is. For some reason though, it just does not want to work and I am probably being completely blind, but cannot see why not. I still get blank images in the HTML and filenames of "/img/.jpg" as though $imgset is still passing through a blank. The values are not NULL in the SQL either, they are most definitely blank entries inputted from an inputbox using a _POST in a form elsewhere.
This:
if ($imgset = '') {
Is always setting $imgset to empty. Use comparison instead:
if ($imgset == '') {
Your else is also not needed since in that case $imgset is already set as $result->fields[6];.
Try to verify if the image exists in your path as well
<?php
$imgset = $result->fields[6];
if ($imgset) {
$imgset = $result->fields[6];
$path ='pathtoimages';
if(!file_exists($path.'/'.$imageset.'.jpg'){
$imgset = 'logo';
}
}
else
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
?>
You forgot to compare on the if condition and instead you are assigning an empty value to $imgset. if ($imgset = '') should be if ($imgset == '')
$imgset = $result->fields[6];
if ($imgset == '')
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
you do not need the else part as the value is already assigned in the first statement.
Using a ternary operator it can be done like this:
echo '<img id="imgdisp" src="/img/'.(empty($imgset)?'logo':$imgset).'.jpg" />';
Shorter code at the cost of readability.
This is the reason why it's better to reverse the condition:
if ('' = $imgset)
would have lead to an error.
The answer:
if ('' == $imgset)
//or
if (empty($imgset))
If you are selecting from MYSQL, you can use something like
SELECT *,COALESCE(image,"logo") AS image FROM ....
This way when the results come back and some rows have a NULL image, it will be replaced by "logo" so you don't need the IF logic in your PHP :)