php - Most frequent element in array? - php

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.

Related

execute php code within string

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)

Shorthand For Loop in PHP

I have three-rows code:
echo '<div>';
for ($i=1; $i<=4; $i++) echo $i;
echo '</div>';
Is there any syntax or function let me rewrite above code in only ONE row, for example:
echo '<div>'.(for...).'</div>'; //error
Thanks
Yes its possible, no you dont want to do it:
echo '<div>' . implode('', array_keys(array_fill(1,4,0))) . '</div>';
While readability is completely personal opinion, there are "common" methods, guidelines, and coding standards which are used by a lot of developers.
And while you don't need to adhere to them, it is always up to you or the company you work for, some of these "ways" are just common sense regardless of your personal choice.
Even if there was a way to do it, why would you want to?
How far do you want to go mixing things together for supposed readability?
echo and a loop are completely different things, and should remain separate.
Answer
In answer to your question, no, it is not possible because PHP needs to differentiate between different "things" - functions, echo statements, variable declaration and usage, etc.
The only things you can "mix" are things which PHP allows to be together, like having a variable in a function parenthesis (function($someVar)).
The only thing you could do (and again this has no point, but your choice) is to put it all on one line, like so:
echo '<div>'; for ($i=1; $i<=4; $i++) { echo $i; } echo '</div>';
But that looks terrible.
I want to quickly see different things - "ah an echo, it prints out XYZ", then I want to see a loop separately so I can see easily what the loop is doing.

What will load faster. Converted Variables or $_POST variables?

I'm fairly new to PHP and still don't know some of the most basic basics of PHP so bear with me.
When writing a script; IE: (Plz ignore syntax errors)
if isset($_POST['name']) {$Name = $_POST['nsme'];}
When using this name in the page, which way is better and loads faster??
A:) echo $Name. ' went to the river';
B:) echo $_POST['name']. 'went to the river';
Obviously this is a fictional example, I'm just wondering which way is better whether it be an echo or any other function and if anyone wouldn't mind chiming in on this, I'd be most appreciative and I thank you all once again.
Obviously
echo $_POST['name'].' went to the river';
would be faster, as you are skipping one step of assigning the post variable to a php variable.
echo $_POST['name'].' went to the river';
Will be faster as you are skipping one step.
However if you need to use $_POST['name'] multiple times, second approach will be better.
If you care about speed don't worry you can use any of them ,deference significantly low but creating variable which is used only once is not a good idea
However if you are doing
$Name = $_POST['nsme'];
and using $name variable i am sure you want to read about Singleton variable
and if you are using $name at other place too its perfectly
A direct variable access is always faster. At least the zend lexer has not recognize for dimensions...
At least for multiple uses...
(use always an isset()-check at least else you'll have notices.)
If you have var $foo and make:
$bar = $foo;
It doesn't create another copy of $foo in memory until you change $foo or $bar so you will have almost same var for both.
You will have same speed, but $bar will look better than $_POST['bar'] and with it easier to work.

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.

htmlspecialchars - there must be a better way

My understanding is that all variables should be output through htmlspecialchars() in a view.
Are there any approaches or methods to do this, without having to specify the function on each appropriate line in each view?
The best that I could come up with is to have a helper function as follows:
function html_escape($var)
function h($var)
{
if (is_array($var))
{
return array_map('h', $var);
}
else
{
return htmlspecialchars($var, ENT_QUOTES, 'UTF8');
}
}
But still...this could get very tedious!
Any ideas?
You may have the function h() output the escaped data, rather than return it. Therefore, instead of writing <?php echo h($myvar); ?> you may write <?php h($myvar); ?>. This is now two characters shorter than echoing the variable without converting to entities.
It's an important distinction to note that not all variables must be run through htmlentities/htmlspecialchars, just ones that contain user-supplied content in anyway, that are not already filtered against a rule-set to prevent arbitrary code inclusion.
You could create a helper function to cut down on the typing slightly, or loop all user-supplied input through htmlentities/htmlspecialchars in your controllers before handing them off to the view (though, this will likely be less efficient since it is unlikely every piece of user-supplied input will be displayed)
What you have there is probably the closest you come to an easy escape in allot of situations.
Personally i use a little loop on my variables, if i know i'm going to be using any $_GET variables in my html output, i run this:
<?php
foreach($_GET as $key => $value) {
$_GET[$key] = htmlspecialchars($value);
}
?>
Then start my html tags right after.
Not everything needs to be escaped though, unless the user have any influence on it.
In addition, you could have a script called escape.php, which uses the above method on common variables you use, like $_GET, $_POST, $_COOKIE and so on, then include('escape.php') it in your scripts before use in the html output.
All over it pretty much depends on your taste and what you need for your project.

Categories