PHP - Get values of image URLS outside foreach? - php

I have this php code to check whether an image exists or not.
foreach($pic_switch as $pic_switch_key => $pic_switch_value)
{
if ($pic_switch_value == "no-image")
{
$img_url = 'http://www.reuters.com/resources_v2/images/masthead-logo.gif';
}
else
{
$img_url = $img_location . $pic_switch_key . '.jpg';
}
}
The above code works great.
I would like to echo $img_url outside the foreach. I tried:
echo '<pre>'.print_r($img_url,true).'</pre>';
but it only gives the URL of the last image. I would like to display the URL of all the images. I would like to display all of them outside the Foreach, rather than echo the URL inside it.

When you use foreach this way, you will end up storing the last variable only in the $img_url. So use this way:
foreach ($pic_switch as $pic_switch_key => $pic_switch_value)
{
if ($pic_switch_value == "no-image")
{
$img_url = 'http://www.reuters.com/resources_v2/images/masthead-logo.gif';
}
else
{
$img_url = $img_location . $pic_switch_key . '.jpg';
}
echo '<pre>' . print_r($img_url, true) . '</pre>';
}

I don't understand why you can't echo from within a loop but one method would be to build a string within the loop and echo it later in the script.
It would be neater to build an array of the URLs and echo from within a for loop later.

Related

php loop and main page

I am trying to program a Flat File PHP Dictionary (English -> Spanish).
I've got this up to now:
<?php
$data =
'car;coche
cat;gato
fat;gordo
far;lejos';
if($data) {
$line = explode("\n", $data);
for($i = 0; $i<count($line); $i++) {
$item = explode(";", $line[$i]);
if($_GET['word'] == $item[0]) { echo"<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>"; }
else {echo MAIN PAGE;}
}
}
?>
It is perfect because it opens a loop of pages in one php file:
e.g. http://localhost/?word=fat prints "Fat Gordo"
My problem is when creating the main page http://localhost. I tried with else{ echo "MAIN PAGE";} but, wherever I place it, it prints "MAIN PAGEMAIN PAGEMAIN PAGE".
Any help?
that's because you are looping through every line in $data. Whatever the outcome of the if expression is, after that it just goes on to the next iteration and runs the if statement again.
So if you add the } else { echo "mainpage" to your if, it will echo mainpage everytime when $_GET['word'] doesn't match $item[0] (which obviously at every line if $_GET['word'] is not defined)
To avoid this you can add something like this:
if($data && !empty($_GET['word'])) {
(...)
} else {
echo "mainpage";
}
If you have a big dictionary it's also good to break you loop once you have found a matching word:
if($_GET['word'] == $item[0]) {
echo "<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>";
break;
}

How to sort floats in an array?

I tried sort, Ksort, multiSort, nothing is working and I'm not sure why.I can use print_r and see that it is an array but it won't sort just keeps giving errors. I think it is because the values are floats but I may be wrong.
Here's a page with the array shown using print_r function:
http://forcedchange.testdomain.pw/gallery/
Here is my code:
<?php
$uploads = wp_upload_dir(); //Path to my gallery uploads folder
if ($dir = opendir($uploads['basedir'].'/gallery-2')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
$images = ksort($images); /* not working */
// echo '<pre>';
// echo print_r($images);
// echo '</pre>';
foreach($images as $image) {
echo '<figure><img src="';
echo $uploads['baseurl'].'/gallery-2/'. $image;
echo '" alt="" /></li>';
echo '<figcaption>';
echo '<p>' . erq_shortcode() . '</p>';
echo '</figcaption>';
echo '</figure>';
}
?>
Try using natsort($images) (don't know which result you want). It should sort the array like:
1.png
2.png
...
9.png
10.png
...
20.png
Assigning won't work because the sort-funcs return a bool... the sorting is done direct inside the given array.
$images=glob("/path/*.{jpg,png,gif}");
ksort($images);
foreach($images as $image)
{
...
... do something with basename($image);
...
}

PHP foreach loop read files, create array and print file name

Could someone help me with this?
I have a folder with some files (without extention)
/module/mail/templates
With these files:
test
test2
I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).
But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.
This is how I try to achieve this, without luck:
foreach (glob("module/mail/templates/*") as $templateName)
{
$i++;
$content = file_get_contents($templateName, r); // This is not working
echo "<p>" . $content . "</p>"; // this is not working
$tpl = str_replace('module/mail/templates/', '', $templatName);
$tplarray = array($tpl => $content); // not working
echo "<option id=\"".$i."\">". $tpl . "</option>";
print_r($tplarray);//not working
}
This code worked for me:
<?php
$tplarray = array();
$i = 0;
echo '<select>';
foreach(glob('module/mail/templates/*') as $templateName) {
$content = file_get_contents($templateName);
if ($content !== false) {
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
} else {
trigger_error("Cannot read $templateName");
}
$i++;
}
echo '</select>';
print_r($tplarray);
?>
Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.
The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.
Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.
You have a typo where you are referring to $templatName rather than $templateName.
$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
$i++;
$content = file_get_contents($templateName);
if ($content !== FALSE) {
echo "<p>" . $content . "</p>";
} else {
trigger_error("file_get_contents() failed for file $templateName");
}
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);

Change attribute using php & querypath

I want to use PHP & QueryPath to find all images in a document, then modify its src like this:
I want to change
http://test.com/test/name.jpg
to
http://example.com/xxx/name.jpg
I can find the specific class name using
$qp2 = $qp->find('body');
Now when I want to find all img on it to change the src:
foreach ($qp2->find('img') as $i) {
//here change the src
}
But when I execute
echo $qp2->html();
I see only last image. Where is the problem?
Like this?
foreach($qp2->find('img') as $key as $img) {
echo $img->html();
}
Sometimes you have to use top() or end() when you are re-using the qp object. Something like:
$qp = htmlqp($lpurl);
foreach ($qp->find('img') as $key => $img){
print_r($img->attr('src'));
$url = parse_url ($img->attr('src'));
print_r($url);
echo '<br/>';
if (!isset($url['scheme']) && !isset($url['host']) && !empty($url['path'])){
$newimg = $htmlpath . '/' . $url['path'];
$img->end()->attr('src', $newimg);
echo $img->html();
}
}
foreach ($qp->top()->find('script') as $key => $script){
print_r($script->attr('src'));
$url = parse_url ($script->attr('src'));
print_r($url);
if (!isset($url['scheme']) && !isset($url['host']) && !empty($url['path'])){
$newjs = $htmlpath . '/' . $url['path'];
echo '<br/>';
echo 'this is the modified ' . $newjs;
}
}

Best way to implement PHP constants in Javascript

So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>

Categories