execute php code within string - php

This question is just for me to learn from. I can easily resolve it outside of the echo...but there MUST be a way to perform a basic calculation or function call within an echo statement...right?
$CurrentMembershipYear = '2016';
echo '<h2>Two-Year Membership for '.$CurrentMembershipYear.' and '.intval($CurrentMembershipYear)+1.'</h2>';
This should be echoing "Two-Year Membership for 2016 and 2017" but instead is generating errors. Usually I would just pre-calculate the second value before the echo statement and just pass it as a variable...but surely there is a way to put this calculation inline?

never mind...bone-headed brain asleep. Just needed parenthesis...I had only tried curvy braces:
$CurrentMembershipYear = '2016';
echo '<h2>Two-Year Membership for '.$CurrentMembershipYear.' and '.(intval($CurrentMembershipYear)+1).'</h2>';

parenthesis should solve it
(intval($CurrentMembershipYear)+1)

Related

access php variable through concatenation

I was trying to achieve something simple and was wondering if it was possible. Google search proved unhelpful this time. Probably it's not possible, but I am not sure. I have the following code:
<?php
//Enter your code here, enjoy!
$query1="yay";
$query2="it";
$query3="works";
for($x=1;$x<=3;$x++){
$query="\$query".$x; //I need to assign the above variables
echo $query;
}
?>
I want the output to be "yayitworks" but instead I get "$query1$query2$query3". Is there any way to get my result? I know a switch statement will help me achieve this, but am just curious.
Thanks in advance...:-)
What you want is variable variables: http://php.net/manual/en/language.variables.variable.php
$query = ${"query".$x}

PHP Generate Random String In Echo

I'm looking for a bit of assistance in generating a random string of numbers that is 4 digits long. To better explain my situation, here is a snippet of PHP code where I need the random numbers inserted (for those wondering about the $ssh->exec I'm using phpseclib).
echo $ssh->exec("touch $username-$port.txt");
The above $port variable is where I'd like PHP to generate a random 4 digit number (preferably between 5000-5999).
After looking at the documentation on W3Schools, it looks like they recommend using the following to generate a random number between defined limits, like so:
echo(rand(10,100));
This works standalone, but the problem with that is it requires an echo and I'm already performing an echo $ssh->exect with my above PHP code. So I'm not quite sure how I would implement an "echo inside an echo" if that makes sense.
If anyone would be willing to help me out with this, it would be greatly appreciated.
You can use a pre-defined variable such as:
$port = rand(5000,5999);
that will then populate through your exec provided you keep it encapsulated inside double quotes. Otherwise, you will need to concatenate.

Any reason why someone would use printf() for pretty much everything?

I am taking over a project from an existing programmer who, to be honest, left the project in a massive heap of unmaintainable, unreadable mess (edit/clarification: dozens upon dozens of standalone .php pages that are a soup of php/html/css that all reference one giant 1500 line 'functions.php' file, ack)
That being said, it seems that pretty much everywhere there is a variable, array, etc. he used printf().
For example, instead of using:
foreach($thing as $t) {
echo "<option value='".$t."'>".$t."</option>";
}
He would use something like:
foreach($thing as $t) {
printf("<option value='%s'>%s</option>", $t, $t);
}
Does anyone have any insight as to why exactly he would do this? Is there some unknown benefit that I am not aware of by using printf() instead of echo/print?
Please note that this isn't just for values that might need to be validated/scrubbed, but for EVERYTHING. Data pulled from the database, random variables and arrays that were defined elsewhere, absolutely everything is printf() instead of just echo or print, and i'm trying to figure out why he would use this method as it might help me understand the logic behind some of the things he built.
"The only reason to use printf() in preference over echo or print() is if you will be using the format string place-holders feature with additional arguments (one for each such place-holder). If not, then print() will be faster, and echo even (very slightly) faster since it does not generate a return value."
Found here: echo VS printf
I imagine he did it for code read-ability. I think using printf/sprintf is more readable than
embedding variables directly into string and alternating '"""''""''".
Personally I think this is the most readable method:
<?php foreach($thing as $t): ?>
<option value="<?php echo $t ?>"><?php echo $t ?></option>
<?php endforeach; ?>
It has the added benefit of looking nice in most IDEs
Well i would have definitely used printf in your example. I often use printf, sprintf, or strtr when outputting html elements with a lot of attributes or complex ones. Its just more readable and its much easier to swap out the values later.

php - Most frequent element in array?

This is the function:
function mostFrequent($x) {
$counted = array_count_values($x);
arsort($counted);
return(key($counted));
}
This is the call in the tag:
<?php
$x=mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
echo "$x";
?>
This should work right? Also, how do I avoid having to use the temp $x for the echo and just echo the result of the function call directly?
Your solution seems reasonable.
<?php
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
?>
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
however, it seems wrong way and using a "temp" variable would be better.
Eventually you will learn that it is better to separate business logic from presentation logic.
So, the business of your business logic turns out to be exactly collecting these "temp" variables for the later use in the presentation logic.
also note that variables in PHP require no quotes to address. you are confusing them with strings.
echo $x;
is the proper syntax.

What is the best way to capture data returned from a function in PHP?

I am new to programming and learning with Wordpress.
the_title(); //outputs the title of the page
I want to capture the title of the page into a string variable so I can manipulate it with strtolower and str_replace functions.
The only way I have gotten it to work is with output buffering.
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
What am I doing wrong?
If what you really are looking for is the wp_title function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
$mytitle = wp_title(null, false);
Otherwise, your only option is to find the function you're looking for and modify the source code.
There is no easier way. Your function does not return the string, it prints it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
Wordpress is a HORRIBLE app to learn how to program from. It uses these global functions that "just work" but they do very specific tasks "inside 'The Loop'". As I say, this is a horrible example of what good code should be.
Thankfully (for you) there are other functions that just return the part you're looking for. Rather than me just writing what you need, you can read a full listing here. Take care that you note down which must be within the mythical Loop and which you can use anywhere.
As it happens there are even more ways to get the title, but I was really imagining for this example you would do something like:
$this_post = get_post($post); // I *think* $post is the post ID inside the loop though I could be wrong
echo $this_post->post_title;
But as another poster (correctly) says you can use a fairly simple wp_title() function to grab the current loop title.
This brings me back to perhaps wanting to explain why learning programming from Wordpress is a bad idea. They have so many damned way of doing the same damned thing that it's almost impossible to keep on top of things.
A blog is a really simple set of data (even moreso in WP's case because it isn't fully normalised) but rather than just having one way to output a title <?php echo $post->title; ?> you have umpteen ways, all doing subtly different things.
If you really want to learn how to program (instead of hacking your way around the crap that is the WP internals), creating a simple blog engine is fairly quick and fun... It's certainly how a lot of people get into a new language or framework.
And if you really want to have fun, have a look at Django.
Enough of the Wordpress rant. If you're fighting something like this in the future that doesn't have 100 ways of doing it, I really wouldn't recommend output-buffer-capturing. It uses up a whole buttload of resources for something relatively simple.
The easiest way can be as simple as just taking the source for the original function, sticking it in a new function and replacing the echo with return.
Just note there may be some database connectivity to handle that returning prematurely may break... So if the echo isn't the last statement, instead of returning right there, store the string as a variable and return at the end of the function.
just figured Id share my final solution with you guys.
This was to give my body tags unique id's in wordpress.*/
$title =wp_title(null,false);
echo strtolower(str_replace(' ','-',ltrim($title)));
//without the ltrim() 2 dashes are created before the title.
Almost every 'the_*' function in Wordpress has a 'get_the_*' counterpart. So, you just have to use
echo str_replace(" ","-",get_the_title());
And it's going to work like a charm. there's also get_the_excerpt(), get_the_content() and the_permalink() which somehow breaks the naming convention (God knows how many times I've written "get_the_permalink()" and got frustrated on why it didn't work)
Cheers!

Categories