Only add item as needed in PHP array - php

I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:
//Add Flair Containers as needed
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
It prints correctly, where content = $flair1, $flair2, and so on.
<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>
But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?

Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.
Like so:
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
if (empty($flairCode)) continue;
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};

I suspect that you could simply prepend if($flairCode) to your echo statement. That would make your inner loop:
foreach($flair as $flairCode){
if($flairCode) echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
Some points to note:
Since the $flair array will always be the same, construct it outside of the loop (this will let you evaluate the condition only once too.
Using $fQty++ is not enough to guarantee unique ID's, especially since every time it hits the while the value is reset. I suggest $fQty should not be part of the while condition and simply stay as an independent tally.
Stop using double-quotes. They're slow.

Related

Compare 2 strings in PHP

I'm in trouble because i can't figured it out how to find my answer.
I'm creating a wordpress website and i have a search engine
I've created an option in my admin panel and code something to write in my option table, but my problem is now
firstly i grab my options from my database with
$mysynonymvalue = get_option( 'synonym-custom' );
I precise that it returne to me something like this ( mango, apple, banana)(this is an example of course)
My Url is something like this :
http://supserwebsite/wordpress/?sfid=2675&_sf_s=toto
Or this
http://superwebsite/wordpress/?sfid=2675&_sf_s=virtualisation cloud devops
so i've created a variable to catch the queries
$motsclefs3= $_GET['_sf_s'];
Now i want to compare the string $mysynonymvalueconvert with $motsclefs3 to find if it match so i write
if (strpos ($mysynonymvalue, $motsclefs3) ){
echo '<script >
$(document).ready(function(){
$(".vc-tabs-li:nth-child(2)").get(0).click();
});
</script>';
}
else{
echo '
<script >
$(document).ready(function(){
$(".vc-tabs-li").get(0).click();
});
</script>';
};
};
The solution seem to work correctly but i can't have the first result, it coompare indeed with all the results but not my first one.
And it doesn't work so fine because with only one letter it return a match ( for example 'a')
Any solution ?
Thanks
*provided url(s) are not accessible.
Solution:
Create a dictionary of option from db and then search the element which you are looking.
So far i move up a bit !So i came with this
I still have
$mysynonymvalue = get_option( 'synonym-custom' );
$mysynonymvalueconvert = preg_split('/[,]+/',$mysynonymvalue);
To grab my words from my database and to convert it into an array.
(the point of this is to get elements that were wrote by an user elsewhere on the admin panel of wordpress)
I also still have
$motsclefs3= $_GET['_sf_s'];
To grab my actual queries ( that will serv me to compare ). I precise that it return me a string. To be more specific, an URL like this (http://mywebsite/wordpress/?sfid=2675&_sf_s=examen) return me (in string) "examen".
Now my point is still to compare if
$motsclefs3;
is inside
$mysynonymvalueconvert
So i've created a "for" loop like this
for ($i = 0; $i <= count($mysynonymvalueconvert); $i++){
if(in_array($motsclefs3, $mysynonymvalueconvert)){
echo'yes';
break;
}
else{
echo 'no';
break;
};
};
But i'm still blocked, this return "yes" only if it match with the first element from
$mysynonymvalueconvert
So any ideas to help me ?
Thanks!

While echo - dont write mutiple lines, overwrite one instead

im trying to write a loop that displays the counter on one line, been sitting here for over an hour but cant figure it out.
The main loop is
while($counter< 100){
echo $counter;
usleep($timeInSeconds*1000000);
$counter=$counter+1;
}
Now this prints 100 numbers after a delay each on a new line. Is it possible for the echo to instead replace itself for each loop?
I tried many options, here is one that didnt crash:
while($counter < 100){
$counter=$counter+1;
echo $counter;
usleep($timeInSeconds*1000000);
flush();
ob_flush();
}
However, with this option it works in one line with a delay, but it doesnt clear the previous echo, so its just a bunch of number next to each other
Could someone help me out?
You are trying to do something on the server that should be done on the client.
I expect you are making a timer. You should write some JavaScript code instructing the web browser on how to display multiple numbers with a delay in between. Your current code will show a loading wheel and a blank screen for the entire duration on many browsers.
Instead, replace your loop with something like:
var time_in_seconds = 1; // You can replace 1 with the value of the PHP variable
var count_element = document.getElementById("example_counter");
var n = 0;
var interval_id;
function update_counter(){
n += 1;
if (n >= 100) {
clearInterval(interval_id);
}
count_element.textContent = n;
}
interval_id = setInterval(update_counter, time_in_seconds * 1000);
<span id="example_counter"></span>

Writing PHP variable based on jQuery calculations and displaying predetermined value

Context:
I'm trying to make an automatically generated list that has a different amount of items on each page. Each item needs a name and a link, based on its place on the list. Here's an example with two items for the problematic part:
PHP variables:
$item_link_1 = "link1";
$item_name_1 = "first item";
$item_link_2 = "link2";
$item_name_2 = "second item";
jQuery:
$("#items").each(function(i) {
$(this).find("a").attr("href", "<?php echo $item_link_"+ ++i +";?>");
});
$("#items").each(function(i) {
$(this).find("a").text("<?php echo $item_name_"+ ++i +";?>");
});
HTML output:
<div id="items">
first item
second item
</div>
Problem:
Obviously, $item_name_"+ ++i +"; will never work. I need a way to add the number generated by jQuery to the end of the variable and echo this new variable.
So, if it's the 4th item, the variable will be $item_name_4. The value of this variable (set manually) will be displayed by jQuery with the text() function.
At least that's my idea for how to automate the process. If there's a way to do this, please tell me. If you know a better way, please tell me.
The problem your having is the difference between server-side processing and client-side processing.
An easy way to think about this is that PHP is handled before the HTML is even put on the screen replacing all the PHP parts with their variable contents. meaning that adding that php text with a client-side language like javascript won't be able to execute the php code and achieving the results you're after.
Luckily your example can be done explicitly in php:
<?php
$links = array(
array('link' => "Link1", 'name' => "first item"),
array('link' => "Link2", 'name' => "second item")
);
?>
<div id="items">
<?php for($i = 0; $i < count($links); $i++){ ?>
<?php echo $links[$i]['name']; ?>
<?php } ?>
</div>

Accessing HTML unordered list elements in PHP

I'm trying to access unordered list elements in php so I can insert them in a database, I need to be able to access them via position but I'm not sure how to do this in PHP. I'm using jQuery so that the list is sortable on the client side.
In Javascript it would be accessed with
alert($("#sortable li:first").text() + ' is first ' + $("#sortable li:eq(1)").text() + ' is second ' + $("#sortable li:eq(11)").text() + ' is last');
The list I'm using is on http://jsfiddle.net/mMTtc/
I'm simply looking for help as for how to store those list items in a php variable i.e. lets say I wanted the 6th element based on how the user had ordered the list.
How would I do this?
Thanks
Using the following code you can send updates to the PHP backend as the user changes the order of elements in the front-end:
$("#sortable").on("sortupdate", function() {
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
var dataStr = '{"newOrder":' + JSON.stringify(dataArr) + '}';
$.ajax({
url: "<url_to_php_file>",
data: dataStr
});
// alert(dataStr);
});
Live example (frontend part): here
You'll have to replace <url_to_php_file> with the path to your PHP file that does the processing of the elements order (i.e. saving them in the DB). The file will be able to access the user-defined order in a normal PHP Array, using json_decode($_POST["newOrder"]), i.e.
...
$newOrder = json_decode($_POST["newOrder"]);
for ($i = 0; $i < count($newOrder); $i++) {
echo("The item labeled '" . $newOrder[$i] . "' is placed by the user at index " . $i . ".\n";
/* 1st item: index 0 */
/* 2st item: index 1 */
/* ... */
}
Example:
You present a sortable list to the user, containing items: item1, item2, item3 (in this order).
The user places item2 before item1, at which point an AJAX call is made passing to the server the array ["item2", "item1", "item3"] (note the order). The above snippet would echo:
The item labeled 'item2' is placed by the user at index 0.
The item labeled 'item1' is placed by the user at index 1.
The item labeled 'item3' is placed by the user at index 2.
(Of course, instead of echoing anything, you would update the value of an index-field in the DB for each item or do something useful.)
You can use DomDocument to parse your HTML. This can be done either via a string using loadHTML(), or loading an external HTML file using loadHTMLFile().
This example uses loadHTML():
<?php
$html = '<html>
<body>
<ul id="sortable">
<li class="ui-state-default">1</li>
<li class="ui-state-default">2</li>
<li class="ui-state-default">3</li>
<li class="ui-state-default">4</li>
<li class="ui-state-default">5</li>
<li class="ui-state-default">6</li>
<li class="ui-state-default">7</li>
<li class="ui-state-default">8</li>
<li class="ui-state-default">9</li>
<li class="ui-state-default">10</li>
<li class="ui-state-default">11</li>
<li class="ui-state-default">12</li>
</ul>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
</html>';
$dom = new DomDocument;
$dom->loadHTML($html);
$li = $dom->getElementsByTagName('li');
// Print first item value
echo $li->item(0)->nodeValue;
// Print third item value
echo $li->item(2)->nodeValue;
Here's what I'd do, and it's certainly not the cleanest way, but it should work.
This assumes you're working with your own pages, and not the scenario where you're getting the page html via http request to some external site (e.g. via CURL) and needing to parse it. DOMDocument serves just fine for the latter case. This solution is for the former, as I'm assuming that since you're working with javascript on the client-side of it, it's probably your own page (unless you're injecting that javascript into the page after it's loaded).
First of all, inside each list item, I'd include a server-side accessible input tag. It will serve to keep track of the position and value, and pass it to the server-side script on form submission.
<form method="POST">
<ul id="sortable">
<li class="ui-state-default">1
<input id="the_list_item_1" name="the_list_item[]" type="text" value="1_0" style="display: none;">
</li>
...
</ul>
</form>
The value is the item's actual value (the example had them ranged 1 - 12) and it's position separated by an underscore (value + "_" + position);
The list needs to be inside a form variable if you only need to submit the list to the server for processing when the user's done. However, if you intend to only use Ajax to get that data to the server, this solution isn't really necessary (as you'd simply just use jquery to get each position and value pair and send them directly in your ajax call).
You'll need to handle updating these input tags as the user drags items and changes the ordering of the list. See here if you need to know how to work with the sortable events. Perhaps, on update, for each list item call this function with the new position:
function update_pos(value,pos)
{
$("#the_list_item_"+value).val(value+"_"+pos);
}
So on form submit, we're now on the PHP side.
$list_items = $_POST["the_list_item"]; // This is basically an array of all the list_items, thanks to naming all the list items with "the_list_item[]", note the empty subscript (square braces).
$ordered_list_items = array(); // Let's push them into an associative array.
foreach($list_items as $li)
{
$li_split = explode("_",$li);
if(count($li_split) <= 0)
continue; // maybe you'd want to handle this situation differently, it really shouldn't happen at all though. Here, I'm just ignoring nonsensical values.
$item_id = $li_split[0];
$pos = $li_split[1];
$ordered_list_items[$item_id] = $pos;
}
// Then later you can shoot through this list and do whatever with them.
foreach($ordered_list_items as $item_id => $pos)
{
// postgres perhaps. Insert if not already there, update regardless.
pg_query("insert into the_list_item (item_id,position) select '$item_id','$pos' where '$item_id' not in (select item_id from the_list_item where '$item_id' = item_id limit 1));
pg_query("update the_list_item set position = '$pos' where item_id = '$item_id'");
}
Of course, all that said, depending on your needs you may need to be reloading this data onto the page. So looping through your db results (perhaps, for that user), you'd output each list_item into place.
$list_items = pg_fetch_all(pg_query($sql)); // $sql needs to be the query to get the results. Probably should order by position ascending.
$lic = count($list_items);
?>
<html> and stuff
<form method="POST">
<ul id="sortable">
<?php
for($i = 0; $i < $lic; $i++)
{
$li = $list_items[$i];
echo "<li class=\"ui-state-default\">".$li["item_id"]."<input id=\"the_list_item_".$li["item_id"]."\" name=\"the_list_item[]\" type=\"text\" value=\"".$li["item_id"]."_".$li["position"]."\" style=\"display: none;\"></li>";
}
?>
</ul>
</form>

getting javascript error object required

Iam getting offsetwidth of an div tag. Below is code.
<body>
<div id="marqueeborder" onmouseover="pxptick=0" onmouseout="pxptick=scrollspeed">
<div id="marqueecontent">
<?php
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// List your stocks here, separated by commas, no spaces, in the order you want them displayed:
$stocks = "idt,iye,mill,pwer,spy,f,msft,x,sbux,sne,ge,dow,t";
// Function to copy a stock quote CSV from Yahoo to the local cache. CSV contains symbol, price, and change
function upsfile($stock) { copy("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1c1&e=.csv","stockcache/".$stock.".csv"); }
foreach ( explode(",", $stocks) as $stock ) {
// Where the stock quote info file should be...
$local_file = "stockcache/".$stock.".csv";
// ...if it exists. If not, download it.
if (!file_exists($local_file)) { upsfile($stock); }
// Else,If it's out-of-date by 15 mins (900 seconds) or more, update it.
elseif (filemtime($local_file) <= (time() - 900)) { upsfile($stock); }
// Open the file, load our values into an array...
$local_file = fopen ("stockcache/".$stock.".csv","r");
$stock_info = fgetcsv ($local_file, 1000, ",");
// ...format, and output them. I made the symbols into links to Yahoo's stock pages.
echo "<span class=\"stockbox\">".$stock_info[0]." ".sprintf("%.2f",$stock_info[1])." <span style=\"";
// Green prices for up, red for down
if ($stock_info[2]>=0) { echo "color: #009900;\">↑"; }
elseif ($stock_info[2]<0) { echo "color: #ff0000;\">↓"; }
echo sprintf("%.2f",abs($stock_info[2]))."</span></span>\n";
// Done!
fclose($local_file);
}
?>
<span class="stockbox" style="font-size:0.6em">Quotes from Yahoo Finance</span>
</div>
</div>
</body>
below is the javascript function which will be called onlaod of the page.
<script type="text/javascript">
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// Set an initial scroll speed. This equates to the number of pixels shifted per tick
var scrollspeed=2;
var pxptick=scrollspeed;
function startmarquee(){
alert("hi");
// Make a shortcut referencing our div with the content we want to scroll
var marqueediv=document.getElementById("marqueecontent");
alert("marqueediv"+marqueediv);
alert("hi"+marqueediv.innerHTML);
// Get the total width of our available scroll area
var marqueewidth=document.getElementById("marqueeborder").offsetWidth;
alert("marqueewidth"+marqueewidth);
// Get the width of the content we want to scroll
var contentwidth=marqueediv.offsetWidth;
alert("contentwidth"+contentwidth);
// Start the ticker at 50 milliseconds per tick, adjust this to suit your preferences
// Be warned, setting this lower has heavy impact on client-side CPU usage. Be gentle.
var lefttime=setInterval("scrollmarquee()",50);
alert("lefttime"+lefttime);
}
function scrollmarquee(){
// Check position of the div, then shift it left by the set amount of pixels.
if (parseInt(marqueediv.style.left)>(contentwidth*(-1)))
marqueediv.style.left=parseInt(marqueediv.style.left)-pxptick+"px";
// If it's at the end, move it back to the right.
else
marqueediv.style.left=parseInt(marqueewidth)+"px";
}
window.onload=startmarquee();
</script>
when iam running the above code on server, iam getting javascript error as "object required" at line 46 also the alert("marqueediv"+marqueediv); is "marqueedivnull" after that alert iam getting the javascript error.
Here my question is, did the div tag is not getting recognized?why?
so that only it is getting as null object, how can i resolved this?
Thanks.
You are calling startmarquee immediately and trying to assign its return value (undefined) to window.onload.
Presumably the script appears in the <head> and this the div does not exist at the time you run it.
Assign the function to onload, not its return value.
window.onload=startmarquee;
You could copy the script and put it before the body closing tag and remove window.onload=startmarquee(); thus making sure all elements have been loaded and accessible
Just like #Quentin said, that element with the id might not have been loaded into the DOM when you referenced it

Categories