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 = ''.$nombre_ocurrencia.'';
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
}
?>
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.
Related
I have an array composed of files of a folder.
When I use the following snippet :
foreach($myarray as $key => $value)
{
echo $value. "<br>";
}
I have the following output :
vendor/templates/File1.docx
vendor/templates/File2.docx
vendor/templates/File3.docx
My question is : how to make it to put each value of my array in a new variable ? How to make it automatically if I have e.g 100 files in my folder ?
Actually I'd like to have (if my array is only composed of 3 items) :
$a = 'vendor/templates/File1.docx'
$b = 'vendor/templates/File2.docx'
$c = 'vendor/templates/File3.docx'
I guess I should use a loop but after many tests, I'm still getting stuck..
Have you any ideas ?
Thanks !!
Here is the solution:
<?php
$myarray = ['vendor/templates/File1.docx', 'vendor/templates/File2.docx', 'vendor/templates/File3.docx'];
foreach($myarray as $key => $value)
{
$varname = "var".$key;
$$varname = $value;
}
echo $var0."\n";
echo $var1."\n";
echo $var2."\n";
->
vendor/templates/File1.docx
vendor/templates/File2.docx
vendor/templates/File3.docx
May be following function will work for your problem.
extract($array);
http://php.net/extract
I have an array called $alldata
If I do this
echo $alldata[0][6][0]["COLOUR"];
It successfully returns the colour. I want to access the value without using the name / label "COLOUR"
I tried this, but it fails with undefined offset
echo $alldata[0][6][0][0];
Re-index so you can use a numeric index:
echo array_values($alldata[0][6][0])[0];
Or for them all:
$result = array_values($alldata[0][6][0]);
echo $result[0];
echo $result[2];
You have to use foreach for this, since the array key is "COLOUR" and not 0.
here's an example on how to solve your problem.
<?php
$alldata = array(
0=>array(
6=>array(
0=>array(
"COLOR"=>"test"
))));
print_r($alldata);
foreach ($alldata[0][6][0] as $key => $value) {
echo $key . "=>" . $value;
}
?>
if you want to use the third key, then you can add a counter to it, by defining $x outside of the foreach and $x++; in the foreach.
I have some problems using stripslashes() on array.
Here is my array :
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse",
10=>"Franche-Comté",
(...)
21=>"Provence-Alpes-Côte d'Azur",
22=>"Rhône-Alpes",);
In order to stripslash, I have adapted this PHP code :
foreach ($tabRegion as $key=>$region) {
$tabRegion[$key] = stripslashes($region);
}
After in the file, I generate URL with it for example :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
But the fact is that the last value of the array is always selected ("Rhône-Alpes") by the code... I don't know why.
Do you have an idea? :)
Thank you !
You are using foreach loop then you have to generate url in that loop.
In that loop you will get each region value
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse");
foreach ($tabRegion as $key=>$region)
{
$tabRegion[$key] = stripslashes($region);
print "<br>".$region;
}
Output will be :
Alsace
Aquitaine
Auvergne
Basse-Normandie
Bourgogne
Bretagne
Centre
Champagne-Ardenne
Corse
So that,you have to insert following line in that for loop :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
You are using $region variable in foreach loop and you should know that it is treated like any other variable in your script. So for example:
$fruit = 'Banana';
foreach(array('Tomato', 'Orange') as $fruit) {
echo $fruit;
}
echo $fruit; // it will output 'Orange';
I'm trying to make a universal script that adds keywords to my individual pages (since header is in an include file) so I am getting the end of the url (multi.php) and retrieving the desc etc. from it's array. For some reason instead of returning keywords or descriptions it instead just returns "m" . . . it's kind of random and has me scratching my head. Here's what I got
<html>
<head>
<title>Multi-Demensional Array</title>
<?php
$path = pathinfo($_SERVER['PHP_SELF']);
$allyourbase = $path['basename'];
$pages = array
(
"multi.php" => array
(
"keywords" => "index, home, test, etc",
"desc" => "This is the INDEX page",
"style" => "index.css"
),
"header.php" => array
(
"keywords" => "showcase, movies, vidya, etc",
"desc" => "SHOWCASE page is where we view vidya.",
"style" => "showcase.css"
)
);
?>
</head>
<body>
<?php
foreach($pages as $key => $value)
{
if($key == $allyourbase)
{
echo $key['desc'];
}
}
?>
</body>
</html>
The reason why this is happening is because in PHP if I had the following code:
$hello = 'world';
and I attempted to do the following:
echo $hello[0];
PHP Would treat the string as an array and return me whatever is in position 0, which would result in w, when your using a foreach your asking PHP to set the key of the array to $key, and it's value to $value.
you then echo echo $key['desc'];, as the value is a string, php sees it as an integer based index, so it will ignore your call for desc and then return the first index, if you were to change echo $key['desc'] to echo $value['desc'] which is a hash based array it will return the desired results.
You should just be able to do this:
if(isset($pages[$allyourbase]))
{
echo $pages[$allyourbase]['desc'];
}
No need for the loop
try
echo $key['desc'];
replace with
echo $value['desc'];
Other people have provided some great solutions, but it's important that you understand exactly what is happening here, so you don't make the same mistake again. Pay careful attention to the comments, and you will be on your way to successful coding!
Here's what is happening:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
// At this point: $key = 'multi.php'
// Also: $value = array( ... );
// Keep in mind: $key['desc'] = $key[0] = 'm';
// You are grabbing the first letter of the 'multi.php' string.
// When dealing with strings, PHP sees $key['desc'] as $key[0],
// which is another way to grab the very first character of 'multi.php'
echo $key['desc'];
// You really want $pages[$key]['desc'], but below
// is a better way to do it, without the overhead of
// the loop.
}
}
If you kept the loop, which is really unnecessary, it would look like this:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
echo $value['desc'];
}
}
The best solution is to replace the loop with the following code:
if (isset($pages[$allyourbase])) {
echo $pages[$allyourbase]['desc'];
} else {
// error handling
}
If I'm reading this right, echo $key['desc']; should be echo $value['desc'];.
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.