Get input avg(example:2,4,3) to find the average - php

I'm trying to figure out how if the user input like : avg(2,3,6,1)
and then the server will respond with the answer which is : Average of (2,3,6,1) is 3.
Here is my simple work and got stuck about the next implementation.
if($r['$msg']="avg(".$i")"){ //if message is avg(2,3,6,1)
$i = array($i);
$avg = array_sum($i) / count($i);
echo "<div class='msg'>Server : $avg</div>";
How to make it works? Sorry for the 'noob' code.

You can do it with explode function in php. Convert the String to array. Check the below code, it will helps.
In your code $i = array($i); will output like Array ( [0] => 2,3,6,1 )
instead of creating 1-D array, you are creating 2-D array.
$i = "2,3,6,1";
//$r['$msg'] = "avg(".$i.")";
$i= explode(",",$i);
//$i = array($i);
print_r($i);
$avg = array_sum($i) / count($i);
echo "<div class='msg'>Server : </div>";
echo $avg;

Related

how to display a string pattern using php loops

my question is how to display string as a pattern using php loops like, if the string is computer,on first iteration it will display "c" and then second iteration it will display like "co" and so on.My following code given below.please give a solution.
<?php
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo $array[$i]."<br>";
}
?>
output will print like this
c
co
com
comp
compu
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo substr($array,0,$i+1)."<br>";
}
$array = "computer";
$count = strlen($array)-1;
$out='';
for($i=0;$i<=$count;$i++)
{
$out .= $array[$i];
echo $out."<br>";
}
Have a nice day :-)
You can use substr($array, 0, $i + 1) instead of $array[$i]. Visit to: PHP: substr for more information.

PHP - Help in FOR LOOP

I have an array and looping through it and pushing the data using for loop.
$test_data = [10,20,35,01,50,60,87,12,45,86,9,85];
Actually that's a sample data. But my data is a result similar to that which I get from PostgreSQL, a single column data.
Using the below function for $test_data.
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'] = $test_data[$x];
}
Result : {"data1":{"data": 85"}}
Here's the for loop which I use along the PostgreSQL result in the PHP.
for( $x=0; $x < pg_num_rows($query); $x++ ) {
$data['data1'] = pg_fetch_assoc($query);
}
Even here I get only the last row in the browser when I do - echo json_encode($data);
Something similar to the result what I've mentioned above.
First 9 rows are not getting inserted into the data[]. Only the last row is getting added to the array.
Please say me where I'm doing the mistake.
Thanks in advance.
Since arrays cannot have same key as index.
You need to rewrite it as ..
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'][] = $test_data[$x];
// ^^ <--- Add that.
}
As Loic suggested go with a foreach , I answered quickly so it didn't strike on my mind in the first place
foreach($test_data as $val)
{
$chart_data['data1'][] = $val;
}
You could do like this (without using pg_num_rows):
// better initialize the result array
$data = array('data1' => array());
while ($row = pg_fetch_assoc($query)) {
// here is the point, add element to the array
$data['data1'][] = $row;
}

how to add letters of the name as array elements in php?

i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}

How to add variables that are passed on through the URL to an array?

<?php
$i = $_GET['i'];
echo $i;
$values = array();
while ($i > 0)
{
$expense = $_GET['expense_' + i];
$amount = $_GET['amount_' + i];
$values[$expense] = $amount;
i--;
print_r($values);
}
?>
i represents the number of sets of variables I have that have been passed through from the previous page. What I'm trying to do is add the expenses to the amounts and put them in an array as (lets just say for this example there were 3 expenses and 3 amounts) [expense_3 => amount_3, expense_2 => amount_2, expense_1 => amount_1]. The names of the variables are successfully passed through via the url as amount_1=50, amount_2=50, expense_1=food, expense2=gas, etc... as well as $i, I just dont know how to add those variables to an array each time.
Right now with this code I'm getting
4
Array ( [] => ) Array ( [] => ) Array ( [] => ) Array ( [] => )
I apologize if I'm not being clear enough, but I am pretty inexperienced with PHP.
The syntax error you're getting is because you're using i instead of $i - however - that can be resolved easily.
What you're looking to do is "simple" and can be accomplished with string-concatenation. It looks like you're attempting this with $_GET['expense'] + i, but not quite correct.
To properly build the parameter name, you'll want something like $_GET['expense_' . $i], here you can see to concatenate strings you use the . operator - not the + one.
I'm going to switch your logic to use a for loop instead of a while loop for my example:
$values = array();
for ($i = $_GET['i']; $i > 0; $i--) {
$expense = $_GET['expense_' . $i];
$amount = $_GET['amount_' . $i];
$values[$expense] = $amount;
}
print_r($values);
This is following your original logic, but it will effectively reverse the variables (counting from $i down to 1). If you want to count up, you can change your for loop to:
$numVariables = $_GET['i'];
for ($index = 1; $index <= $numVariables; $index++) {
$expense = $_GET['expense_' . $index];
...
Or just serialize the array and pass it to the next site, where you unserialize the array
would be much easier ;)

For Each Key Isn't A Number

So I'm trying to iterate through an XML feed and paginate it but I've run into a problem. When I try to get the index (key) of the current array it outputs a string "campDetails" on every iteration instead of an incrementing integer like 0,1,2,3
Here is a sample of the XML format
<campaigns>
<campDetails>
<campaign_id>2001</campaign_id>
<campaign_name>Video Chat Software</campaign_name>
<url>http://www.fakeurl.com</url>
</campDetails>
<?php
$call_url = "https://www.fakeurl.com";
if($xml = simplexml_load_file($call_url, "SimpleXMLElement", LIBXML_NOCDATA)):
foreach($xml as $i => $offers):
$offer_link = $offers->url;
$offer_raw_name = $offers->campaign_name;
echo $i . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
endforeach;
endif;
?>
Output to be expected:
0 http://www.fakeurl.com
Video Chat Software
Actual output:
campDetails http://www.fakeurl.com
Video Chat Software
EDIT: Thank you for your answers everyone. It seems I was given incorrect information from another question on here. I was told that $i would keep a numerical index for the current iteration.
print_r($xml); (obviously more results but this is the first)
SimpleXMLElement Object ( [campDetails] => Array ( [0] => SimpleXMLElement Object ( [campaign_id] => 2001 [campaign_name] => Video Chat Software [url] => http://www.fakeurl.com/ )
simplexml_load_file returns an object, a foreach loop will iterate over its fields, and $i will hold the current field's key.
If you want a numeric counter as well, just increment on your own:
$j = 0;
foreach($xml as $i => $offer){
// do your stuff
$j++;
}
Its a bit redundant, but you can use something like:
$x = 0;
foreach($xml as $i => $offers):
// other stuff
echo $x . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
$x++;
endforeach;
You can also streamline your echo line like so:
echo "$i $offer_link <br> $offer_raw_name";
In this usage of foreach, $i is not a numeric index but a key. In this case, the key for the current object is campDetails.
Alternative Code
$i = 0;
foreach($xml as $offer) {
// your code...
++$i;
}
For more details on the type of object you receive from simplexml_load read the docs or debug with print_r($xml);.
Your $i is not an index. You could do something like:
$index = 0;
foreach($xml as $i => $offers):
$offer_link = $offers->url;
$offer_raw_name = $offers->campaign_name;
echo $index++ . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
endforeach;
Instead of using the current foreach and associative array, I pushed all values to an indexed array.

Categories