I have an array which contains the categories for a particular article ($link_cat). I'm then using mysql_fetch_array to print out all of the categories available into a list with checkboxes. While it's doing this I want it to compare the value it's on, to a value from the other array. If there is a match, then it means that one of the categories applies to this article, and it should print out a line of code to apply the checked attribute. great! except it's not working =[
while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ){
$cat[$i] = $row['category'];
$cat_id[$i] = $row['cat_id'];
echo '<li><input type="checkbox" ';
$catCount = count($link_cat);
for ($ct = 0; $ct < $catCount; $ct++){
if ($cat_id[$i] == $link_cat[$ct]){
echo 'checked="checked" ';
}
}
echo 'name="' . $cat_id[$i] . '" />' . $cat[$i] . '</li>';
$i++;
}
I've never really done a nested loop before (I suspect thats the problem).
The problem seems to be that when this runs, $link_cat[0] which will have the first category to check against in it - doesn't register. It comes up blank. Printing out variables inside the for loop confirmed this. Any others [1] [2] etc, are fine. It's just [0]. But why? it doesn't seem to make any sense. I know there is something in there, because I printed the contents of array as I filled it it, just to check. Yet it doesn't just show during the loop. Any ideas?
slight bug fix (and blatant style change): Your version can print out checked="checked" multiple times. Do $cat and $cat_id need to be arrays?
while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ) {
$cat = $row['category'];
$cat_id = $row['cat_id'];
echo '<li><input type="checkbox" ';
if ( in_array($cat_id, $link_cat) ) {
echo 'checked="checked" ';
}
echo "name='$cat_id' />$cat</li>";
}
For situation where one would normally throw a debugger at a problem, I like to throw in a nice print_r in a comment block (view-source for debug output, safer on live-ish sites).
echo '<!-- ' . print_r($link_cat, TRUE) . ' -->';
While I was originally very wrong about the array looping needing a reset, I can't shake the feeling that looping through that array isn't the fastest way to do what you are after.
Perhaps array_search would do, or maybe array_key_exists. in_array look like a winner but I didn't think of it
Related
So, guys, my problem is that i'm creating an array from a mysql column, but, when i echo the array items, it returns me nothing, i'm about this for a while and i'm not seeing a possible error, hope can get some help. Here' s my code: (I know about the mysql to mysqli, but i'm just beginning and trying the logical stuff. :))
$duracao = mysql_query(
"SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 AS mysum
FROM afunda_eleva_$a"
); //THIS $duracao IS INSIDE A FOR LOOP THAT EXECUTES THE QUERY IF A CONDITION IS SATISFIED (DEPENDING ON $a and $prevNum), it is working fine!
while ($row2 = mysql_fetch_assoc($duracao))
{
$duracao_afunda_eleva[] = $row2['mysum'];
}
so, to test some possible problems, i've put:
$i2 = sizeof($duracao_afunda_eleva);
echo $i2;
echo <br>;
which returns me the right size of the array, the problem comes here, i think:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo"
. mysql_error());
echo "<br>";
}
and this returns me no value. I really would appreciate any suggestion. Thanks in advance!
Try print_r instead of echo - echo outputs (string)$variable, which in case of an array is just "array". Also, echo is a language construct and not a function, so your or die(...) is problematic, as language constructs don't have return values.
Generally it's better to not use or die(...) constructs, and handle problems correctly (using a defined return value, so cleanup code can run, for example). Also, not being able to output anything with echo would mean that your php/whatever installation is seriously gone bad, at which point you probably won't even reach that line in your code, and even then it won't have anything to do with mysql.
Since the problem is not in the variable, try to use an alias in your MySQL select:
SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 as mysum
Then in your PHP, you can get $row2['mysum'];
It may not solve the problem, but it is a good start.
Personally I use:
$arr = array ( /* ... */ );
echo "<pre>";
var_dump($arr);
echo "</pre>";
In your last for-loop, you use $i++, it should be $i1++
A quick tip is not to use the sizeof function in your for loop. This gets run with each iteration of your loop and you will notice an improvement in performance if you move it outside the loop (or use a foreach loop instead). e.g.
$count = sizeof($duracao_afunda_eleva);
for($i = 0 ; $i < $count; $i++) {
echo $duracao_afunda_eleva[$i] . '<br />';
}
or
// Foreach loop example
foreach ($duracao_afunda_eleva as $key => $value) {
echo $value . '<br />';
}
or what you could also do is this one line
echo implode('<br />', $duracao_afunda_eleva);
Use this code:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo". mysql_error());
echo "<br>";
}
You increased $i instead of $i1.
Although, with arrays, it's usually easier to use a foreach loop.
This runs from the first to the last element in the array.
Like so:
foreach ($duracao_afunda_eleva as $value) {
echo $value;
}
I would also suggest removing the space in $row2 ['mysum']:
$duracao_afunda_eleva[] = $row2['mysum'];
Edit
Just noticed it now, but your fetch-statement is wrong... It has a typo in it:
while ($row2 = mysql_fetch_assoc($duracao))
Make sure it reads mysql instead of myqsl.
I am working with a couple of arrays that are stored in sessions. The purpose is to be able to add and remove objects from the arrays which will contain recipients to messages posted. It SEEMS to be working okay but with some quirks.
This code allows objects to be added;
while($row = mysqli_fetch_array($result))
{
$contact = $row['contact'];
$userid = $row['userid'];
echo "<tr>";
echo "<td><a href='mypagepost.php?contact=$userid&recipient=$contact' STYLE='TEXT- DECORATION: NONE'><font color=#808080>" . $row['contact'] . "</a></font></td>";
echo "</tr>";
$contact_count++;
}
And this one gives me the ability to send to another page for removal from the respective arrays.
<?php
$isBefore = array();
foreach ($_SESSION['contactlist'] AS $key => $rec)
{
if (!in_array($rec, $isBefore)) {
$isBefore[] = $rec;
echo "<font color=#808080><a href='removerecipient.php?contact=" . $_SESSION['recipientlist'][$key] . "&recipient=$rec' STYLE='TEXT-DECORATION: NONE'>
<font color=#808080>" . $rec . " </a></font>";
}
}
?>
This references a page with the following;
unset($_SESSION['recipientlist'][array_search($contact, $_SESSION['recipientlist'])]);
unset($_SESSION['contactlist'][array_search($recipient, $_SESSION['contactlist'])]);
So, I'm just starting to learn how to use arrays effectively so please forgive me for asking an obtuse question or two. When I click on a recipient just once to add them to the arrays, it works fine. I find that I can click on recipients in a contact list multiple times and the array still allows them to be added over and over again (although it doesn't print them out in the list). When I go to remove them by clicking on their name, I have to click them over and over again until they're gone. How can I set up a situation where it only gets added once and that's it? The other question I have is that after I remove all recipients from an array, I'm still left with an index number with no value. The print looks like this for both arrays (this is after adding and removing three recipients from the list;
Array ( [3] => )
Array ( [3] => )
The indexes don't apear to have a value associated with them, no idea what this means.
You could create a $_SESSION and check to see
if(isset($_SESSION['nameHere'])){
//do your thing here
}
, or make a variable like
$varName = 0;
and when the form is submitted
if(isset($_POST['submitButtonName'])){
if($varName === 0){
$varName = 1;
//do you thing here
}
}
. That $_POST would be a $_GET if your <form method='get' in your HTML.
$icecream = array (
"Choco" => array('2 Dollars'),
"Mango" => array('3 Dollars')
);
print $icecream[0][0];
expected output:
2 Dollars
Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).
I want to use values as keys for the "first array level" ($icecream[0]),
It does output nothing at all. What is my logical flaw with this solution?
try this:
echo $icecream['Choco'][0]
Your problem here is calling the wrong key for the 1st dim
.
.
For your updated question, try this:
$ice_k = array_keys($icecream);
echo $icecream[$ice_k[0]][0];
You're not using the associative array right. You need to use the right key.
echo $icecream['choco'][0];
You can use position but it will be a counter like this:
$counter = 0;
foreach($icecream As $k=>$v) {
echo $icecream[$k][0] . ' [' . $counter . ']';
$counter++;
}
and if you want to get only value you can use previous code
$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
echo $icecream[$ice_k[$position]][0];
}
I'm trying to figure out if I need to do this inside the for loop or outside the for loop but I want to check to see its empty or not first.
echo "<ul>";
for($x = 0; $x <= (count($quotesArray)-1); $x++)
{
echo "<li>".stripslashes($quotesArray[$x]->quote)."</li>";
}
echo "</ul>";
There is something simpler that checking during loop - it filters all the values and is called array_filter() function:
$quotesArray = array_filter($quotesArray);
echo "<ul>";
foreach($quotesArray as $quote){
echo "<li>".stripslashes($quote)."</li>";
};
echo "</ul>";
The above assumes that $quotesArray contains strings (or elements that work correctly in string context) and you do not want only the elements that are evaluated as false when converted to boolean (see more about converting to boolean).
Additionally you can simplify your code further:
$quotesArray = array_filter($quotesArray);
$quotesArray = array_map('stripslashes', $quotesArray);
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
if you know $quotesArray contains at least one element.
EDIT:
Short version, that also checks whether the list should be generated (in other words: whether array contains at least one element after processing):
$quotesArray = array_map('stripslashes', array_filter($quotesArray));
if (!empty($quotesArray)) {
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
};
It needs to be outside the loop because if it is empty, and you don't generate any list items, then you have no list, so you should not generate the ul start and end tags either (since a list with no list items is invalid).
well if you dont wan the list at all then you should do it before the echoing of the first <ul>
if(count($quotesArray) > 0){
//Do your echos and loops in here
}
You can just run both checks.
if($quotesArray){
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote->quote) . '</li>';
}
}
echo '</ul>';
}
When you say you want to check if it's empty, do you mean the entire $quotesArray or one of the values within it?
If you mean you want to check if a value within the array is empty, you could consider this approach:
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote) . '</li>';
}
}
echo '</ul>';
<div class="meta">
<?php echo $submitted."pubblished in".$fenl; ?>
<a href="<?php echo base_path().'comp/'.$node->nid;?>">
<?php echo $comment_count;?>comment</a>
</div>
it there a better way to write the above code.
2,
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
$items = array();
foreach ($terms as $term){
$items[] = $term->name;
}
return $items;
}
could i delete $items = array(); this line. thank you.
Not really, unless you count the short-tags, but they are frowned on.
Technically, it would be created automatically, but you should pre-declare the empty array, it should generate a warning if you did not.
NB. If you have two separate questions, they should be asked separately in future.
What about one line?
<?php
echo "<div class=\"meta\">\n{$submitted}published in$fenl\n<a href=\"" .
base_path() . "comp/{$node->nid}\">\n$comment_count\ncomment</a>\n</div>";
?>
You could delete $items = array(); as long as $items isn't used before in your script (just don't return $items in case $terms isn't an array and the foreach loop gets called, as the situation seems to be at the moment). I believe you need to check mysql_query() examples at http://php.net/manual/en/function.mysql-query.php.
It's syntactically pretty okay. As far as I know, you could omit $items = array(); but I find it more readable if you just leave it as it is.
Btw.: Don't you need to use mysql_fetch_assoc for your iteration? mysql_query returns a resource.
echo "<div class=\"meta\">" . $submitted . " pubblished in " . $fenl . "" . $comment_count . " comment</div>";
You don't need to define array. But in this case ( foreach issue. Foreach loop requires an array as parameter to left side the "as". If you delete that line $items wouldn't be an array.It will be a null variable.So you will get a warning. ) it should be defined.