1

I've been strugling with this problem for some time now. I can't figure out whats wrong. Following code is very simple, VISOR_URL is a constant defined in another file. If i echo it outside forearch loop it prints the constant value. If I print it inside the loop it's value gets duplicated. Same problem occurs if I use a variable. Any ideas?. Thanks in advance. Sebastian

<?php
require_once('conf.php');//I require the file where VISOR_URL is defined
//VISOR_URL is defined in conf.php. define('VISOR_URL', $server_ip.'/'.VISOR_NAME);

echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevo

if (!empty($occurrence_ids)) {//occurrence_ids is an array and values are printed fine

    foreach ($occurrence_ids as $key => $value) {
        echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevohttp://192.168.0.15/tncvisornuevo 

        $ocurrencia = new ca_occurrences($value);

        $nombre_ocurrencia = $ocurrencia->get('ca_occurrences.preferred_labels');

        $link = '<a href="'.VISOR_URL.'/views/occurrenceDetails.php?occurrence_id='.$value.'">'.$nombre_ocurrencia.'</a>';

        echo $link."<br>";
    }

}
?>

Following simple example does not duplicate the constant value:

<?php

//Define a constant
define('CONSTANT', 'imaconstant');

echo CONSTANT."<br>"; //Echoes imaconstant

$test_array = array(0,1,2,3,4,5,6,7,8);

foreach ($test_array as $key => $value) {
    echo $value.CONSTANT,"<br>"; //Echoes nimaconstant, n+1imaconstant

}

?>
1
  • 2
    Check that new ca_occurrences($value); or $ocurrencia->get is not outputting the value of VISOR_URL. Commented Apr 18, 2014 at 18:59

1 Answer 1

1

It'll echo it as many times the loop will run. For example -

$array = array('aa','bb','cc');
$var = "abc";

foreach($array as $key => $value);
{
    echo $var.'<br>';
}

/*   
   abc
   abc
   abc
*/

Now above since the array has size of 3, the loop will run 3 times and echoes the variable...ofcourse 3 times.

Sign up to request clarification or add additional context in comments.

4 Comments

OP echos other things in the loop though. echo VISOR_URL; ...; echo $link."<br>";
And if I want to use $var inside the foreach loop?
@sms - I'm printing $var inside foreach only
Yes that's the behavior I expect. But in my first code example it prints abcabc in every loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.