php error count() displays "Array" or "m" - php

I'm trying to display different images from the database that are in the same field but the result is echoed either as "m" or "Array".
Here's my code:
$badges = $row['badges'];
$badges = explode(",", $badges);
$badge = count($badges);
if(empty($badges)) {
$badges = "";
} else {
$i = 0;
while($i <= $badge) {
$badges = "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badges."</td></tr>";
$rank is then echoed to the div that I want it to be displayed but the image src is always "m" or when I try putting the while in place of the $rank variable it echoes as "Array". Does anyone know why this is?

I would use another variable name, like badgeString as the output. Also, it seems like you want to append all the badges
if(empty($badges)) {
$badgeString = "";
} else {
$i = 0;
while($i <= $badge) {
$badgeString .= "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badgeString."</td></tr>";

Related

Display error when condition not matched inside foreach

I am displaying data from mysql using foreach but there is also a if condition inside the for each. I want to display a message if this condition is not matched. the code is below;
<?php
// some other codes to connect data base etc.
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$lon[$i] = $row['lng'];
$lat[$i] = $row['lat'];
$status[$i] = $row['status'];
$title[$i] = $row['title'];
$property_id[$i] = $row['property_id'];
$price[$i] = $row['price'];
$availability[$i] = $row['availability'];
$type[$i] = $row['type'];
$bedrooms[$i] = $row['bedrooms'];
$lounges[$i] = $row['lounges'];
$type[$i] = $row['type'];
$time[$i] = $row['time'];
$i++;
}
for($i=0; $i<$count; $i++) {
$distance = Haversine($my_lat, $my_lon, $lat[$i], $lon[$i]);
if($distance < $radius) {
echo 'Display data';
} else{
echo "error message";
}
}
?>
After displaying message following this code:
if($distance < $radius) {
I want to display message if this condition is not met but nothing seem to work so far.
if($distance<$radius){
echo "This statement meets the criteria.";
}else{
echo "This statement doesn't meet the criteria.";
}
You should check the basics on how if/else works before diving into this.
Before make sure that your datatype is define.
http://php.net/manual/en/function.settype.php
Try not allow empty data:
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
After verify mojore points, simplify your conditions by:
elseif($distance >= $radius){
Like this you avoid Unexpect values.
first you print $distance and $radius and after put if condition so you can confirm what actually happened...

Php removing specific special character and php algorithm ideas

so I ended up with this project, that,due to my opinion, is some levels greater than my skills, so I would like you to help me.
This project's functionality is to write some words in those 4 columns,which have to be combined.The words that are in the same column mustn't be combined. You can only combine words with the rest of the columns.
I will give you the full code so you can see what I have done.
The second question I have is how you delete a special character(in this case, the "\n")
<?php
if(isset($_POST['submit']))
{
if(isset($_POST["separator"])){$separator= $_POST["separator"];}
if(isset($_POST["match"])){$matchType = $_POST["match"];$matchArr = array();
foreach($matchType as $match)
{
$matchArr = $match;
}}
$j=0;
$columnCount=array();
$wordArr[] = array();
$wordArrRows[] = array();
$protasi="";
$wordsCombinations = 1;
$wordsCounter = 0;
for($i=0; $i<4; $i++)
{ $words=0;
$enterChar=0;
if(isset($_POST["in$i"]) && !empty($_POST["in$i"]))
{
$input=$_POST["in$i"];
$enterChar = substr_count($input,"\n");
$words= $enterChar+1;
if($words>0)
{
$wordArr[$j]= explode("\n",$input);
$wordArrRows[$j]= $words;
$j++;
}
$wordsCombinations*=$words;
}
}
$i2=0;
$columnCounter = array_fill(0, $j, "0");
while($wordsCounter < $wordsCombinations)
{
if($i2<sizeof($columnCounter) && $columnCounter[$i2] < $wordArrRows[$i2])
{
echo "grammi: ".$i2." <br>";
$i=0;
for($i=0; $i<$j; $i++)
{
//echo "wordArr[".$i."][".$columnCounter[$i]."]".$separator;
echo $wordArr[$i][$columnCounter[$i]]." ";
}
$columnCounter[$i2]++;
if($columnCounter[$i2] >= $wordArrRows[$i2] ){$columnCounter[$i2]=0;}
echo "<br>";
}
$i2++;
if($i2>=sizeof($columnCounter)){$i2=0;}
$wordsCounter++;
}
}
?>
(NOTE: don't use the radio buttons or the check boxes, they're not functional).
EDIT
What is the expected result for that example?
The second question: trim() to delete "\n"

Distinguish between elements and last element of array

Im creating tablerows based on the number of the array colours:
$query = mysql_query("SELECT * FROM things);
$num = mysql_num_rows($query );
$colours = array ();
if($num)
{
for ($i = 0; ($row = mysql_fetch_assoc($query)); ++$i)
{
$colours[$i] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; ($i < ($arrlength)); ++$i){
echo "
<tr class='border_bottom'><td>".$colours[$i]."</td></tr>
";
}
So, if colours is, lets say, equal to 8, 8 table rows with the class border_bottom are created.
border_bottom is used by CSS to add a border to the bottom of each tablerow.
What I need is some PHP help: I need code which checks the array colours. The last element of the array has to go with an empty id since I dont want a border-bottom added to that very last tablerow. All other tablerows have to go with the border_bottom class, tho.
I was thinking of starting the code like that:
echo"
<tr class='
";
-->PHP code goes here<--
echo"
'>
<td>".$colours[$i]."</td></tr>
Try this:
<?php
$query = mysql_query("SELECT * FROM things");
$num = mysql_num_rows($query);
$colours = array();
if($num)
{
while($row = mysql_fetch_assoc($query))
{
$colours[] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; $i < $arrlength; ++$i){
if($i < $arrlength - 1){
echo "<tr class='border_bottom'><td>{$colours[$i]}</td></tr>";
}else{
echo "<tr><td>{$someColor}</td></tr>";
}
}
Try the following code in your table row echo
echo "<tr"
.($i < $arrlength - 1 ? " class='border_bottom'" : "")
.">"
."<td>{$colours[$i]}</td></tr>";
You can actually do this while fetching the rows without needing to count how many there are, by reading ahead one row.
$previous_row = mysql_fetch_array(); // fetch the first row (if there is one)
while ($previous_row) {
if ($row = mysql_fetch_array()) {
// if another row is fetched, then the previous row was NOT the last row
echo '<tr class="border_bottom"><td>' . $previous_row['colours'] . '</td></tr>';
} else {
// otherwise, the previous row WAS the last row, and does not get the class
echo '<tr><td>' . $previous_row['colours'] . '</td></tr>';
}
$previous_row = $row; // Set the previous row to the current row
}

Unexpected variable scope in PHP

I would like to show 3 random images from database in my website. Below is its code:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd () {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd();
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd();
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
But whenever I run this code, I get the error below:
Undefined variable: my_array in line ... // The first line of makernd() function.
But I expected $my_array to be an accessible array for this function.
What's the problem?
To simply fix your problem, you should pass $my_array to makernd() as a parameter:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd ($my_array) {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd($my_array);
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd($my_array);
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
HOWEVER, I strongly suggest putting the randomization in MySQL, to
Simplify your code
Significantly improve the performance, and
Eliminate excessive loops & recursion in PHP
Example:
$sql = "SELECT id,url
FROM tbl_gallery2
ORDER BY RAND()
LIMIT 3";
$query = mysql_query ($sql);
if (mysql_num_rows($query) >= 3) {
while ($r = mysql_fetch_row($query)) {
echo '<img src="./images/slider/' . $r[1] . '.jpg" alt="" class="slider" />';
}
}
PS - I also suggest you update your code to use mysqli, as mysql is deprecated
PPS - I also suggest you look into mysqli_fetch_assoc so you can reference query results by name instead of index (e.g. $r['url'] instead of $r[1] - as if you ever change the order of your query, you will break references by index.

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories