Making code more efficient and less a copy and paste - php

I've been working on a piece of code that that pulls the name of a guild and with it the information of boss/monsters said guild has killed in an online game. There are many many monsters in this game and every one has three difficulty settings. I have managed to get the code to do what i want however it has an enormous amount of copy and paste and ive only done about 1/5 of the total amount of enteries. I really cant think how to make this code less of a giant bloat. This is the code for just one monster for the 3 difficulty settings as you can see it's alot just for one. there are probably another 60 of these!. Can anybody help me understand better ways to do this. Thanks!
$sql = 'SELECT * FROM `phpbb_profile_fields_data`';
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
/////////////////////////////////// START - 8 MAN BONETHRASHER
$normal = '';
$hard = '';
$nightmare = '';
/////// START - CHECK NORMAL
if ($row['pf_kp_em_no_bonethr'] == '1')
{
$normal = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
}
else if ($row['pf_kp_em_no_bonethr'] == '2')
{
$normal = '';
}
else if (is_null($row['pf_kp_em_no_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NORMAL
/////// START - CHECK HARD
if ($row['pf_kp_em_ha_bonethr'] == '1')
{
$hard = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
}
else if ($row['pf_kp_em_ha_bonethr'] == '2')
{
$hard = '';
}
else if (is_null($row['pf_kp_em_ha_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK HARD
/////// START - CHECK NIGHTMARE
if ($row['pf_kp_em_kn_bonethr'] == '1')
{
$nightmare =' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
else if ($row['pf_kp_em_kn_bonethr'] == '2')
{
$nightmare = '';
}
else if (is_null($row['pf_kp_em_kn_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NIGHTMARE
if ($normal == '' && $hard == '' && $nightmare == '')
{
}
else
{
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}
}
$db->sql_freeresult($result);

I'm still slightly fuzzy at what you are trying to do, but I'll give helping you out a shot.
You could probably get away will creating a class that does all of this.
For example:
class checks {
public function checkBosses($normalBoss, $hardBoss, $nightmareBoss) {
$difficulties = array();
$difficulties['normal'] = array('boss' => $normalBoss);
$difficulties['hard'] = array('boss' => $hardBoss);
$difficulties['nightmare'] = array('boss' => $nightmareBoss);
foreach ($this->difficulties as $difficulty -> $boss) {
$this->difficulties[$difficulty]['result'] = checkDifficulty($boss['boss'], $difficulty);
}
$normal = $this->difficulties['normal']['result'];
$hard = $this->difficulties['hard']['result'];
$nightmare = $this->difficulties['nightmare']['result'];
if ($normal == '' && $hard == '' && $nightmare == '') {
return null;
} else {
return array(
'normal' => $normal,
'hard' => $hard,
'nightmare' => $nightmare,
);
}
}
protected function checkDifficulty($boss, $difficulty) {
if ($difficulty == 'normal') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
} else if ($difficulty == 'hard') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
} else if ($difficulty == 'nightmare') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
if ($boss == '1') {
return $image;
} else if ($boss == '2') {
return '';
} else if (is_null($boss)) {
echo "Boss was set as NULL This should not happen!";
} else {
echo "Sosia messed up go hit him in the face.";
}
}
}
Then all you would need to do is call:
$checkResult = checks::checkBosses($row['pf_kp_em_no_bonethr'], $row['pf_kp_em_ha_bonethr'], $row['pf_kp_em_kn_bonethr']);
if ($checkResult != null) {
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}

If you can retrieve an array of bosses, you can do a foreach loop on them to run that same bit of code for each boss like this:
foreach ($bosses as $boss) {
//Full code to be repeated for each boss here
}

Related

Loop isn't working for my Twitter API

I have a setup where it favourites and retweets a specific tweet. For some reason, the code works for the favourites however retweets do not. Can anyone see the issue?
$method = 'statuses/retweet/'.$url[3];
$amt = "26";
$sub = rand(1,3);
$amt1 = $amt-$sub;
if($_POST['favorite'] == "true" || $_POST['favorite'] == "1"){
for ($x1=1; $x1<=$amt1; $x1++)
{
$content = $connection[$x1]->post('favorites/create', array('id' => $url[3]));
}
}
if($_POST['retweet'] == "true" || $_POST['retweet'] == "1"){
for ($x2=1; $x2<=$amt; $x2++)
{
$content = twitteroauth_row('statuses/retweet/'.$url[3], $connection[$x2]->post($method), $connection[$x2]->http_code);
}
}
have you tried declaring
$amt = 26
instead of
$amt="26"
EDIT:
for ($x2=1; $x2<=amt; $x2++)
{
$content = twitteroauth_row('statuses/retweet/'.$url[3], $connection[$x2]->post($method), $connection[$x2]->http_code);
}
you have used amt instead of $amt in the loop condition

PHP Issue - function output is 000

I've been trying to make a CLI application that logs Yahoo! messenger login dates/times for certain users using a third party, but this isn't really getting anywhere. Even though checking iself works when used individually, it does not seem to when using the while & foreach too. checkAvailability outputs "000". Could anyone please fix this and perhaps optimize it?
<?php
error_reporting(E_ALL);
$users[0] = "|59|62|157|85|218|78|135|43|63|145|151|173|157|93|107|90|84|129|140|110|55|28|210|212|80|128|252|127|15|192|223|154|177|39|129|191|62|17|113|236|2|168&t=0.23704720849047";
$users[1] = "|70|255|229|124|194|244|242|223|73|250|184|237|222|251|8|243|104|4|70|125|205|177|229|255|178|244|123|251|13|157|220|47|88|247|15|0&t=0.04614829820959876";
function checkAvailability($user){
$dataGot = file_get_contents("http://www.imvisible.ro/getstatus.php?id=".$user);
$fullText = explode("|", $dataGot);
$status_coded = $fullText[0];
echo $status_coded;
return $status_coded;
}
while(true) {
foreach($users as $user) {
$user['oldstatus'] = $user['status'];
if (checkAvailability($user) == "1" and $user['oldstatus'] != "online") {
$user['status'] = "online";
echo "online";
} elseif (checkAvailability($user) == "3" and $user['oldstatus'] != "invisible") {
$user['status'] = "invisible";
echo "invisible";
} elseif (checkAvailability($user) == "2" and $user['oldstatus'] != "offline") {
$user['status'] = "offline";
echo "offline";
} else {
$user['status'] = "error";
echo "error";
}
if ($user['status'] != $user['oldstatus']) {
echo $user." a fost detectat ca ".$user['status']." la ".date(DATE_RFC822).".\n";
}
}
sleep(60);
sleep(60);
}
An endless runing CLI application in PHP in not the best solution. Its better when you make a cronjob and run the script every one or every to minutes. Then you can store the status or what you need in a database or a file.
I have looked at your scripted and test the script:
<?php
error_reporting(E_ALL);
$users[0] = "|59|62|157|85|218|78|135|43|63|145|151|173|157|93|107|90|84|129|140|110|55|28|210|212|80|128|252|127|15|192|223|154|177|39|129|191|62|17|113|236|2|168&t=0.23704720849047";
$users[1] = "|70|255|229|124|194|244|242|223|73|250|184|237|222|251|8|243|104|4|70|125|205|177|229|255|178|244|123|251|13|157|220|47|88|247|15|0&t=0.04614829820959876";
function checkAvailability($user){
$dataGot = file_get_contents("http://www.imvisible.ro/getstatus.php?id=".$user);
$fullText = explode("|", $dataGot);
$status_coded = $fullText[0];
return $status_coded;
}
while(true) {
foreach($users as $key => $user) {
$userStatus[$key] = checkAvailability($user);
if(!isset($userStatusRet[$key]['oldstatus'])) {
$userStatusRet[$key]['oldstatus'] = '';
}
if(!isset($userStatusRet[$key]['status'])) {
$userStatusRet[$key]['status'] = '';
}
$userStatusRet[$key]['oldstatus'] = $userStatusRet[$key]['status'];
if ($userStatus[$key] == "1" and $userStatusRet[$key]['oldstatus'] != "online") {
$userStatusRet['status'] = "online";
echo "User ".$key.": online\n";
} elseif ($userStatus[$key] == "3" and $userStatusRet[$key]['oldstatus'] != "invisible") {
$userStats['status'] = "invisible";
echo "User ".$key.": invisible\n";
} elseif ($userStatus[$key] == "2" and $userStatusRet[$key]['oldstatus'] != "offline") {
$userStatusRet[$key]['status'] = "offline";
echo "User ".$key.": offline\n";
} else {
$userStatusRet[$key]['status'] = "error";
echo "User ".$key.": error\n";
}
}
sleep(5);
}
Its not the best solution but the problem in your case is, that you can't write in the $user output. I have made here a new variable with the user id as iterator. When you run the script you can see the output:
User 0: online
User 1: offline
User 0: online
User 1: error
User 0: online
User 1: offline

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';
}

Add substr max length to my function

Below is a code snippet from the file I am working with. I will start by saying I have attempted to find out on my own many times with failure, I am not a coder but I wish I knew more. I need some help figuring out how to add a substr length to the string $forum
This function outputs the latest 5 forum topics. The problem I'm having is the topic titles are to long for where the widget is being placed, so I wanted to truncate it to max 35 characters displayed. Can you help me? I know I'm a newb!
function sf_recent_posts_tag($limit=5, $forum=false, $user=true, $postdate=false, $listtags=true, $forumids=0, $posttime=false, $avatar=false, $size=25)
{
global $wpdb, $current_user, $sfvars;
$limit = sf_esc_int($limit);
if (empty($limit)) return;
sf_initialise_globals($sfvars['forumid']);
$out = '';
$forum_ids = '';
# are we passing forum ID's?
if ($forumids != 0)
{
$flist = explode(",", $forumids);
foreach($flist as $thisforum)
{
if (sf_can_view_forum($thisforum))
{
$forum_ids[] = $thisforum;
}
}
} else {
# limit to viewable forums based on permissions
if($current_user->forumadmin == false)
{
$allforums = sf_get_forum_memberships($current_user->ID);
if ($allforums)
{
foreach ($allforums as $thisforum)
{
if (sf_can_view_forum($thisforum->forum_id))
{
$forum_ids[] = $thisforum->forum_id;
}
}
} else {
return '';
}
}
}
# get out if nothing to see
if($current_user->forumadmin == false && empty($forum_ids)) return '';
# create where clause based on forums that current user can view
if ($forum_ids != '')
{
$where = ' AND '.SFPOSTS.".forum_id IN (" . implode(",", $forum_ids) . ") = 1 ";
} else {
$where = '';
}
$sfposts = $wpdb->get_results("SELECT DISTINCT topic_id
FROM ".SFPOSTS."
WHERE post_status = 0 ".$where."
ORDER BY post_id DESC
LIMIT ".$limit);
if($sfposts)
{
foreach($sfposts as $sfpost)
{
$postdetails = sf_get_last_post_in_topic($sfpost->topic_id);
$thisforum = sf_get_forum_record($postdetails->forum_id);
$p=false;
# Start contruction
if($listtags) $out.="<li class='sftagli'>\n";
if ($avatar)
{
if ($postdetails->user_id)
{
$icon = 'user';
if (sf_is_forum_admin($postdetails->user_id)) $icon='admin';
} else {
$icon = 'guest';
}
$out.= sf_render_avatar($icon, $postdetails->user_id, sf_filter_email_display($postdetails->user_email), sf_filter_email_display($postdetails->guestemail), false, $size);
}
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
if($forum)
{
if ($p == false) $out.="<p class='sftagp'>";
$out.= __("posted in forum", "sforum").' '.sf_filter_title_display($thisforum->forum_name)." "."\n";
$p=true;
}
if($user)
{
if($p == false) $out.="<p class='sftagp'>";
$poster = sf_build_name_display($postdetails->user_id, sf_filter_name_display($postdetails->display_name));
if(empty($poster)) $poster = sf_filter_name_display($postdetails->guest_name);
$out.=__("by", "sforum").' '.$poster.' '."\n";
$p=true;
}
if($postdate)
{
if($p == false) $out.="<p class='sftagp'>";
$out.=__("on", "sforum").' '.sf_date('d', $postdetails->post_date)."\n";
if ($posttime)
{
$out.=' '.__("at", "sforum").' '.sf_date('t', $postdetails->post_date)."\n";
}
$p=true;
}
if($p) $out.="</p>\n";
if($listtags) $out.="</li>\n";
}
} else {
if($listtags) $out.="<li class='sftagli'>\n";
$out.='<p>'.__("No Topics to Display", "sforum").'</p>'."\n";
if($listtags) $out.="</li>\n";
}
echo($out);
return;
}
I can't find where you get the post titles in your code, but to truncate a string to 35 chars you simply need something like $truncated = substr($title, 0, 35)
You may find it helpful to append '...' to the truncated titles:
$truncated = substr($title, 0, 35).'...';
EDIT:
without seeing a lot of code that you have omitted it's hard to say, but I suspect it's a matter of changing
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
to
$out.= substr(sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index), 0, 35).'...';

php foreach results

foreach ($flr_array as $flr) {
if (!($flr = trim($flr)))
continue;
//list($flr, $keyword) = explode('|', $flr, 2);
$ip = '';
$err_msg = isValidFLR($flr, $ip);
if (!$err_msg) {
list($randlink, $lastid, $scr) = addLink($flr, $ip);
$flr = stripslashes($flr);
$url_array[$i]['number'] = $i + 1;
$url_array[$i]['flr'] = $flr;
$url_array[$i]['flr_substr'] = (strlen($flr) > 33) ? substr($flr, 0, 33) . '...' : $flr;
$url_array[$i]['randlink'] = $randlink;
$url_array[$i]['fullrand'] = $config['indexurl'] . $config['mod_rewrite_char'] . $randlink;
$url_array[$i]['scr'] = $scr;
$url_array[$i]['id'] = $lastid;
$url_array[$i]['flr_length'] = strlen($flr);
$url_array[$i++]['randlink_length'] = strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink);
////
//$smarty->assign("flr_length", strlen($_REQUEST['flr']));
//$smarty->assign("randlink_length", strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink));
////
} else {
js_alert($err_msg);
}
}
In function isValidFLR these is part of captcha check:
if ($config['captcha_check']) {
if (verifyCaptcha() == false) {
return 'Wrong code!';
}
}
Let's say in textarea i enter:
google.com
google.de
google.net
and enter wrong captcha code, so it gives me 3 messages of Wrong code!
It's happen i think because of foreach. Any ideas how to make in foreach display only one error message ?
Your question is hard to understand but I think you are right (in the foreach)....
if err_msg <> '' then you should put a break in your code to get out of the foreach (if that is what you want).
else {
js_alert($err_msg);
break; //this will break out of for loop
//or return false if it a function
}

Categories