Echoing PHP Array Returns no Result - php

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.

Related

Using explode in another foreach

I've been using explode in a separate foreach, but now I want to use it in existing foreach, which I find hard. Instead of the name of the screenshot it echos "Array". What am I doing wrong and how can I limit it to just one of the screenshots, not up to four?
<?php $game = Yii::app()->db->createCommand();
$game->select = 'idProgramGame, dk_name, dk_text, picture, recordType, screenshot';
$game->from = 'programsgames';
$game->where = 'dk_name IS NOT NULL';
$game->where = 'featured = 2';
$game->where = 'points = 100';
$game->where = 'recordType = "g"';
$game->order = 'date DESC';
$game->limit = '1';
$gameresult = $game->query();
foreach($gameresult as $gamerow) {
echo '<a href="http://www.domain.com/Yii/index.php/programsgames/';
echo $gamerow['idProgramGame'];
echo '">';
echo '<br><div class="image"><h2><span><b>';
echo $gamerow['dk_name'];
echo '</b></span></h2>';
echo '<center><img src="http://www.domain.com/upload/';
echo explode(';',$gamerow['screenshot']);
echo '" height="250" align="center" alt="';
echo $gamerow['dk_name'];
echo '"></center>';
echo '</a></div><br><br><br>';
}
?>
When trying to debug, you should always simplify your code as much as possible, while still getting the error.
In this case, you've already established that your echo explode(";",$gamerow['screenshot']); line is at fault here, so you should investigate explode and how it works.
In particular, you'll notice that it returns an array. Reading up on arrays will tell you that if you try to just echo it, it outputs Array, literally.
Now, I don't know what's in $gamerow['screenshot'], but I'm going to guess that it's something like this:
something.png;otherstuffhere
If that's the case, then your solution depends on if your PHP is up-to-date.
If it is, just do this:
echo explode(";",$gamerow['screenshot'])[0];
If not, you have to use a temporary variable:
$parts = explode(";",$gamerow['screenshot']);
echo $parts[0];
For future reference, to output the contents of an array for debugging purposes, use var_dump or a related function.
echo explode(';',$gamerow['screenshot']);
explode() will return an array of all values seperated by ';', but echo() can't display arrays. You could just loop through that array from explode() using foreach:
foreach(explode(';',$gamerow['screenshot']) as $screenshot){
echo($screenshot);
}

Variable variables with drupal

I am theming a drupal content type, and I have a set of similarly named variables. e.g. field_anp_1, field_anp_2,..., field_anp_10. I want to dynamically print them out from within a for loop. Normally, one would print the values out individually by doing something like:
print $field_anp_1[0]['value'];
in my case, I can't do this because the last number changes. So, within a for loop, how would one print out these fields? I tried variable variables, but I don't seem to understand exactly what is going on there - and I don't think it likes the fact that this in an array. Any help would be greatly appreciated!
Definitely not an array. But you can use a variable as the name of a variable with {..}
ghoti#pc:~ $ cat invar.php
#!/usr/local/bin/php
<?php
$field_anp_3="three";
$field_anp_2="two";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (isset(${$thisvar})) {
printf("%s: %s\n", $i, ${$thisvar});
} else {
printf("%s: not set\n", $i);
}
}
ghoti#pc:~ $ ./invar.php
1: not set
2: two
3: three
4: not set
Alternately, if you are sure that the variables that do exist will be sequential. you can stop on failure (per comments below):
#!/usr/local/bin/php
<?php
$field_anp_1="one";
$field_anp_2="two";
$field_anp_3="three";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (!isset(${$thisvar})) {
break;
}
printf("%s: %s\n", $i, ${$thisvar});
}
I can see no reason for having an untold number of variables generated like that. But this is how you could collect them:
$vars = array();
foreach(get_defined_vars() as $name => $value) {
if(strpos($name, 'field_anp_') === 0) {
$vars[$name] = $value;
}
}
Now you would have your values as an associative array in $vars. Instead of adding the values to $vars, you could print them directly.
Update In response to your comment
$array = array('foo' => 'bar');
$x = 'foo';
$field_anp_bar = 'baz';
echo ${'field_anp_' . $array[$x]};
Ok, I figured it out. I simply needed to be more specific with PHP. To call a variable such as: $field_anp_0[0]['value'] from within a for loop, where 0 is increasing, one simply needs to do the following:
<?php
$numbers = array(123,235,12332,2342);
for($i; $i<count($numbers); $i++){
$var = "field_anp_".$numbers[$i];
printf("%s\n", ${$var}[0]['value']);
}
?>
This will allow me to list the fields that I will need to have printed out in the order I need to have them printed out. Then, I can use a for loop to print out a themed table for instance.
Thank you for the help!

How to reference a item in an array numerically when it has been created as an associative array

I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

How to loop through an array of checkboxes and a MySQL database without overlap?

for($j = 0; $j < $length; $j++){
while($answersRow = mysql_fetch_row($fetch)){
if($answersRow[0] == $curr_answer_id[$j]){
echo "<input type='checkbox' value='$answersRow[0]' checked>$answersRow[1]</input> ";
} else {
echo "<input type='checkbox' value='$answersRow[0]'>$answersRow[1]</input> ";
}
}
}
Assuming $fetch is my result, here's my dilemma. The for loop represents the array of checkboxes. The first loop around, everything works fine. However, any more than that, we no longer cycle through the while loop because of the internal mysql pointer. I know I can move the pointer around using mysql_data_seek(), but don't have an idea on how to do so usefully. If I move it back to 0, then it just outputs everything for as many things that were checked.
I basically want to traverse through for each question through the database but without any overlap. It is a bit hard to explain so I apologize if I am not explaining this simple problem properly; I'll try and clarify if need be.
You can save the results of your first while in an array:
//> FIRST LOOP
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row; //> Saving in the $rows array
//> All your code from your first loop
}
//> SECOND LOOP
foreach($rows as $v) {
//> All your code you need for your second loop without any additional query
}
Also sorry If I misunderstood your question but It is not so clear what you are asking for
Addendum
After reading better your question if I understood correctly you want to achive everything within only one loop. In this case you can save the html you need in the first while like this:
$firstLoop = '';
$secondLoop = '';
while() {
$firstLoop .= '<option> [...]';
$secondLoop .= '<div> [...]';
}
At this point with one loop you have built the html you need and they are in $firstLoop and $secondLoop. This is of course faster then any other solutions

Categories