Returning values outside of a function - php

I have a function which gets some values from Google analytics and prints them to the screen. I need to use these values later on in the file. When i try to assign these values to a variable it is null but the print is displaying the values correctly. An example of the values being printed is
3188, 2530, 2475, 1340, 2184.
function printResults($reports){
global $anna;
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($values[$k] . ", ");
$anna.=$values[$k]. ", ";
}
}
}
So the vaules correctly display using the print but when i try to echo the variable $anna outside of the function it does not.
Ok so after looking at the solution from Don't Panic it became obvious that the variable just needed to be returned. Who would have thought it :) Thanks for the help!
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
//print($values[$k] . ", ");
$anna.=$values[$k]. ", ";
return $anna;
}

I would suggest a different approach. It looks like your function gets all the values from a set of metrics that each contains a set of values, and prints them. If you need to use the set of values, then your function that directly prints them isn't as useful. Make a function that just gets the values and returns them in an array. Be sure to return them!
function getAllValues($metrics) {
foreach ($metrics as $metric) {
foreach ($metric->getValues() as $value) {
$allValues[] = $value;
}
}
return $allValues;
}
I'm assuming the $reports argument in the example in your question is supposed to be $metrics.
Then, you can call this function to get your values.
$values = getAllValues($metrics);
And if you need to print them, just
echo implode(', ', $values);
That way your function does what it says it does.

Related

How do I generate more than one random code

I have typed this up to generate a random code. I am trying to add them into a database as they are generated. How do i modify this code to generate x amount instead of one?
<?php
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($i = 0; $i < 4; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, 35)];
}
if ($i < 3) {
$serial .= '-';
}
}
echo '<p>' . $serial;
?>
for more precise random token. Try adding current timestamp with a text. current Timestamp itself changes every second. therefore it will mostly be unique. A random text adding at front or last can make it even more unique for users working at a same time.
UPDATE: also add a function whether that unique string exists or not.
A pretty cool, easy method, can be something like this too.
<?php
echo md5(microtime());
Ofcourse it is not 100% safe etc but if you need a quick and easy "RANDOM" string it could be usefull.
Concerning your question:
<?php
function genereteRandomKey($count=10)
{
$data = [];
for($i=0;$i<$count;$i++)
{
$data[] = md5(microtime());
}
return $data;
}
var_dump(generateRandomKey());
To do this, we edit your code slightly and wrap it within a function, like this;
function createHash($length = 4)
{
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($it = 0; $it < $length; $it++) {
$serial .= $tokens[ mt_rand( 0, (strlen($tokens) - 1) )];
}
return $serial;
}
The length within the parameter can be left null and will default to 4, just in case you wanted to create longer codes.
To then create more codes, you simply loop via a for loop (Or any loop that you are using!) like so;
for ($i = 0; $i < 5; $i++) {
echo createHash() . '<br />';
}
Obviously, you won't be wishing to echo them out, but instead adding them to a database.
With that in mind, may I also suggest that instead of multiple INSERT queries, to catch them all inside of an array and just do one run on the query, which can be achieved like so;
$inserts = array ();
for ($i = 0; $i < 5; $i++) {
$inserts[] = createHash();
}
$sql = "INSERT INTO `table` (`row`) VALUES ('" . implode('\'), (\'', $inserts) . ");";
Which, in that test run, would output the following as your $sql;
INSERT INTO `table` (`row`) VALUES ('ISS7'), ('SB72'), ('N97I'), ('1WLQ'), ('TF6I);

Why is passing by reference slower in this code?

I've encountered something that seems like a strange performance problem. Running this code:
<?php
function test_ref(&$test)
{
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}
}
function test()
{
$test = array();
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}
return $test;
}
$scriptstart = microtime(true);
$test = array();
test_ref($test);
$sum = 0;
foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}
echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";
$scriptstart = microtime(true);
$test = test();
$sum = 0;
foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}
echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";
?>
I get these results:
sum 548521
time taken 12.37544798851
sum 551236
time taken 0.29530310630798
What's going on here? It seems to be connected to the fact that I insert sub-arrays into the array, though I don't see why passing by reference should be that much slower.
(this is on PHP Version 5.3.3-7+squeeze14 with Suhosin Patch 0.9.9.1)
(edit: fixed using of unset variables, still the same result)
You're accessing values from another scope - that's always slower than only using ones that are defined within the function itself. Here's a nice blog post explaining it, even though that's not its primary topic: PHP internals: When does foreach copy?
It is just my guess but I think we could explain it like this:
when using no reference a local variable is created (that is directly pointing to a memory) and the loop goes like:
$i = 0; $foo = 499; $test[499] = array(); $test[499][] = 2; "commit" directly to a memory
finaly, the value $test is then returned - reading directly from the memory pointer
when using referenced value, the variable passed is like a pointer to a pointer (that is finally pointing to a memory)
in this case the loop looks like:
$i = 0; $foo = 354; $test[354] = array(); $test[354][] = 7; "commit" to a memory via pointer to a memory pointer
I guess therefore there is at least one more step neccessary when working with referenced variables...

How to alter elements in a for loop depending on numbers in an array?

How would I alter certain elements in the inner for loop if I am using an array with numbers?
e.g
$decryptFields[0] = '1';
$decryptFields[1] = '3';
if($z) == ANY OF THOSE NUMBERS IN THE ARRAY DO SOMETHING.
$x[$i][$z]
so if the inner for loop contains any of those numerals then something will happen e.g maybe I'll make the text bold.
foreach($decryptFields as $dfield) {
echo $dfield;
}
for($i = 0; $i< 10; $i++) {
for($z = 0; $z < $columnLength; $z++) {
echo $x[$i][$z];
}
}
}
Your question is not very clear, but I will do my best to answer it.
If you want to 'do something' if the value $z equals any of the values in the array $decryptFields, you can simply use:
if(in_array($z, $decryptFields)){ /*do something*/}
EDIT: It seems $z is also an array of values.
In that case, use :
$intersection = array_intersect($z, $decryptFields);
foreach($intersection as $key=>$value){
echo "<b>$value</b>";
}
Maybe something like...
for ($i = 0; $i < 10; $i++) {
// Build a string
$str = '';
for ($z = 0; $z < $columnLength; $z++) {
$str .= $x[$i][$z];
}
// If any of the elements of $decryptFields are present in the string, wrap
// it in <span class='bold'></span>
foreach ($decryptFields as $dfield) {
if (strpos($str, $dfield) !== FALSE) {
$str = "<span class='bold'>$str</span>";
break;
}
}
// Echo the result
echo $str;
}
If you need to check multiple items for match to any item of some array, best solution is to build index for the array:
foreach ($decryptFields as $key => $value) $decryptIndex[$value] = $key;
And use that index later:
if (isset($decryptIndex[$x[$i][$z]])) {
// Do something
}
And if you need to get index of matching element in $decryptFields array, use $decryptIndex[$x[$i][$z]]
This is the fastest method, since associative array implementation in PHP is very fast.

PHP Return Loop Result

I am new to the world of coding as well as PHP and am wondering how I can use return when looping. For example I would like to return/display 1-10 however not use echo.
$start = 1;
$end = 11;
for($start; $start < $end; $start=$start+1) {
echo $start; //how can I use return?
}
Well, return will exit the function, so if you put return in a loop, the loop will only do one iteration (until the return statement).
You can collect all the values in an array and return the array:
function myFunction() {
$start = 1;
$end = 11;
$values = array();
for($start; $start < $end; $start=$start+1) {
$values[] = $start;
}
return $values;
}
That said, a function generating consecutive numbers already exists: range().
return is for sending the results of a function call back to the function or script that called it. It's the opposite of passing parameters to a function.
What you're doing is looping over a variable in the same scope, so return is not needed. Printing is done via echo or print. However, you may choose to build a value in that loop and print that once the loop is completed.
Additionally, if you're in a loop and you want to stop that loop immediately, use break; and if you want to skip the iteration you're on and go to the next one, use continue.
Here's some additional reading.
More clarification on continue. Say, for whatever reason, we don't want to do anything when $i is 6:
$start = 1;
$end = 11;
for ($i = $start; $i < $end; $i++)
// changed this to iterate over $i for readability/clarity
{
if ($start == 6)
{
// essentially, continue just skips this iteration of
// the loop, goes back to the top, iterates $i based on
// that third parameter in the for() declaration, and
// continues on.
continue;
}
echo $start; //how can I use return?
}
// output: 1234578910
just use
function foobar()
{
$output = '';
for ( $i = 1 ; $i <= 10 ; $i++ )
{
$output .= $i;
}
return $output
}
echo foobar();
You can achieve it by defining a variable you want to return inside and outside the loop with .=.
Here is a working example:
function my_function() {
// I am the variable to be return-ed
$k = "My World<br/>";
for ($z=1; $z<=3; $z++) {
$v = 'Here'.$z;
// I am the same variable but I am going inside the loop
$k .= $v . "<br/>";
}
//I am not always important to be here!
$k .= "Is Awesome";
// This is the show time..
return $k;
}
my_function();
Output:
My World
Here1
Here2
Here3
Is Awesome
Return will end the function that you are currently in. The scenario you have given us is not a good scenario to use the return function.
The example below will do the same as your code, but uses a function as well as your for loop. Hope this answeres your question.
$start = 11;
$end = 20;
for($start; $start <= $end; $start++){
echo calculateValue($start);
}
function calculateValue($value){
return $value - 10;
}
function loop_kec($ar_kec) {
$total_data = count($ar_kec) - 1;
//$return_kec = array();
for ($e = 0; $e < $total_data; $e++) {
$return_kec .= 'kecamatan = ' . "'$ar_kec[$e]'" . ' or ';
}
$return_kec .= 'kecamatan = ' . "'$ar_kec[$total_data]'";
return $return_kec;
}

adding string to all but last item in array

I have an array and I'd like to add a string to each item in the array, apart from the last item.
Any ideas how I'd do this?
Thanks
This should do it for both numerically-indexed arrays and associative arrays:
$i = 0;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ < $c - 1) {
$array[$key] .= 'string';
}
}
If your array is numerically indexed, a simple loop does the job.
for ($i = count($array) - 2; $i >= 0; $i--) {
$array[$i] = $array[$i] . $stringToAppend;
}
I don't think there is a native command for this.
Just do it the traditional way.
// Your array.
$MyArray = array("Item1","Item2","Item3");
// Check that we have more than one element
if (count($MyArray) > 1) {
for ($n=0; $n<count($MyArray)-1; $n++) {
$MyArray[$n] .= " Appended string";
}
}
The code is from the top of my head, so maybe some tweeking might do he trick.
Well a simple for loop would be the obvious thing I guess.
for ( $i=0; $i < count( $myArray )-1; $i++ )
{
$myArray[$i] = "Hey look a string";
}
But then you might also just use array_fill to do a similar job:
array_fill( 0, $sizeOfArray, "Hey look a string" )
Then you can just set the last value to be whatever you want it to be.
EDIT: If by "add a string to each item" you mean you already have a value in the array and you want to append a string, then I would use my first suggestion with $myArray[$i] .= "Hey look a string"; instead of the simple assignment.
$array =array();
$statement = null;
for ($j= 0;$j<count($array);$j++) {
if ($j === count($array)-1) {
$statement .= $array[$j];
} else {
$statement .= $array[$j].' OR ';
}
}

Categories