Sum string length of all array values - php

<?php
setcookie("Auction_Item", "Luxury Car", time()+2*24*60*60);
if(isset($_COOKIE["Auction_Item"])){
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
} else{
echo "No items for auction.";
}
?>
Okay so this php code simply sets a cookie and gives the value, I need to write a function that after accepting a boolean parameter as TRUE returns the sum of length of all cookies presented into the request.
if ($val = true){
$cookies = $_COOKIE
$strVal = "";
$countVal = count($cookies);
for ($x = 0; $x < $countVal; $x++) {
$strVal = $strVal . $cookies[$x].$val
}
echo 'Sum of length of all cookie values' . strlen($strVal)
I've tried this, but it doesn't seem to work.

The answer from MaryNfs is correct but missing one important thing from your original code. Try the following:
setcookie("Auction_Item", "Luxury Car", time()+2*24*60*60);
if(isset($_COOKIE["Auction_Item"])){
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
} else {
echo "No items for auction.";
}
$val = true; //Set the variable $val
//You had $val = true, setting $val to true.
//You need to evaluate it as true or false so use === to compare
//Using = sets the variable's value
if($val===true) {
$joinedCookies = "";
foreach ($_COOKIE as $key=>$value) {
$joinedCookies = $joinedCookies . $value;
}
$joinedCookiesLength = strlen($joinedCookies);
echo 'Sum of length of all cookie values ' . $joinedCookiesLength;
}
Once the $_COOKIE is set, the above should return:
Auction Item is a Luxury Car
Sum of length of all cookie values 36
Your code was missing ; after three lines which would break things so keep an eye out for that as well.

if I got it right, you can get the length of all cookie values like this:
$joinedCookies = "";
foreach ($_COOKIE as $key=>$value){
$joinedCookies = $joinedCookies.$value;
}
echo 'Sum of length of all cookie values: '.strlen($joinedCookies);

To get the total string length of a flat array, implode() the elements using no glue, then call strlen().
No manual looping, no manual concatenation, and no temporary variables.
echo strlen(implode($_COOKIE));

Related

How to create a php variable with text and value of another variable

Want to create a php variable using text before and after the value of another variable.
variable variables. But have only seen examples of assignment with no text.
$vsBOA_W[]=$rows['vsBOA_W'];
// BOA = team 3-char abbreviation. Looking for something similar to above but insert 3-char abbreviations based on a input file.
$numOfTeams = 3; // Determined from external source
$teamAbbr = array("BOA","CAA","CHN"); // For simplicity for this example. This array would normally be created from an external source.
for($i=0; $i<$numOfTeams; $i++) { // I know I can use size of array instead of nunOfTeams. That's not the issue.
echo $teamAbbr[$i]."<br>"; // for testing
$$("vs".{'$teamAbbr[$i]'}."_W[]"} = $rows['$$("vs".{'$teamAbbr[$i]'}."_W"}']; // a total guess
}
I expect the end result to look like:
$vsBOA_W[]=$rows['vsBOA_W'];
for BOA
Update #2: I tried the following (breaking down each step) and get the same error on $$TeamWins assignment.
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
$$TeamWins[] = $TeamWinsHold;
}
Update #3:
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
${$TeamWins}[] = $TeamWinsHold;
}
foreach(${$TeamWins} as $value) {
echo "value=$value<br>"; // only displays last element or value assigned from above loop.
}
Update #4 (final):
$teamW = array();
$teamL = array();
for($i=0; $i<$numOfTeams; $i++) {
//echo $teamAbbr[$i]."<br>";
$teamWName = 'vs' . $teamAbbr[$i] . '_W';
$teamLName = 'vs' . $teamAbbr[$i] . '_L';
//echo "teamWName=$teamWName<br>";
//echo "teamLName=$teamLName<br>";
$teamW[$teamWName] = $rows[$teamWName];
$teamL[$teamLName] = $rows[$teamLName];
}
I don't quite understand the interplay with the rows in your example. But going by your guess assignment, you can always simplify, by forming the variable name upfront:
<?php
$rows = ['xFOOy'=>[], 'xBARy'=>[], 'xBAZy'=>[]];
$items = ['FOO', 'BAR', 'BAZ'];
foreach($items as $abbr)
{
$name = 'x' . $abbr . 'y';
${$name}[] = $rows[$name];
}
But, I'd say you'd be better off with a keyed array than variable variables, as it makes for easier inspection, and there is less chance of namespace clashes.

OOP Issue Stopping PHP Functioning & MySQL Data Array Retrieval Issue

Now a very kind StackOverflow use has helped me out with a lot of my issues however there's two remaining probelms with my code before it's ready to go, any ideas would be great as i'm currently screaming at it:
First of all i'm using the following to try and pull data from a MySQL Database, return it as a Numeric Array and Order It By ID. There's 2 items in there and no matter what I do I can only get 1 to display (I need it to display ALL data when the table fills up more):
$query = "SELECT * FROM batch ORDER by ID";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
?>
Secondly, slightly off topic but this code below was given by a StackOverflow user however I can't get it to work, they've geared it to OOP which is not an area i'm familiar with and no matter what I do to correct the $this-> or public / private it still refuses to work (the aim of the code is to have a number in $userinput which gets checked against the $widgetBatches array for the closest match (i.e. input is 1100 and closest is 1000) this then gets deducted from the input (to leave 100) and the process loops again to check and this time returns 100 as the closest, this process continues until the $userinput reaches 0 or a negative number:
<?php
$userinput = 10000; // Our magic variable - user input
$iterations = 0;
function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array("250", "500", "1000", "2000");
echo "Iteration " . $iterations;
echo "<br/>";
echo "Widget requested: " . $widgetRequested;
echo "<br/>";
$closest = GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";
$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;
echo "<hr/>";
if($widgetRemaining > 0)
{
Widget($widgetRemaining);
}
else
{
echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}
}
function GetClosest($array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}
?>
This:
<?php
function Widget($input) {
$currentValue = $input; // Set internal variable from input (Think of this as an initial "remainder")
$i = 0;
$widgetBatches = [250, 500, 1000, 2000]; // Setup batch array
while ($currentValue > 0) { // While the remainder is more than 0
$i++;
echo "Iteration " . $i . "<br/>";
echo "Widget requested: " . $currentValue . "<br/>";
$closest = GetClosest($widgetBatches, $currentValue); // Find the closest value from batch array
echo "Closest: " . $closest . "<br/>";
$currentValue = $currentValue - $closest; // Work out new remainder
echo "Remainder: " . $currentValue . "<hr/>";
}
// Loop will exit when remainder is less than 0
echo "The value is now below or equaling zero: " . $currentValue . "!";
}
function GetClosest($array, $value) {
$result = null; // Innitialise the returned variable in case of failure
foreach($array as $val) { // For every array value, unless stopped
$result = $val; // Set result to current array value
if($value <= $result) break; // Stop foreach loop if value is less than or equal to result
}
return $result; // Return last result from Foreach loop
}
Widget(9000);
?>
Hopefully the comments are useful... I put more detail in than I would usually...
Did you try fetchAll(), I use PDO so not sure, but would suggest you use a while loop, like:
while ($result = $mysqli->query($query));
Or:
foreach($result as $r) then $r['data'];
I'm %100 sure the loop will iterate and pull out every data, which you can send to a table or a list.

How to concatenate string in php with conditions?

I wrote query in php file ,my query is:
$query = "SELECT cc.NAME complex_check_name,f.name server_name,
sgk.NAME single_check_name,cc.operator
FROM complex_check cc,
lnksinglechecktocomplexcheck lk,
single_checks sgk,
functionalci f ,
lnkconfigurationitemtosinglecheck lkcg
WHERE cc.id = lk.complex_check_id AND
sgk.id = lk.single_check_id and
sgk.id = lkcg.single_check_id AND
lkcg.config_item_id = f.id ";
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
$list= $obj->complex_check_name .
"#".
$obj->server_name .
";".
$obj->single_check_name .
$obj-> operator;
echo $list .'<br>';
}
}
The result is :
test_com_check_sep01#INFRASEP01;cpu check sep01&
test_com_check_sep01#INFRASEP01;DB check sep01&
test_com_check_sep01#INFRASEP01;disk space check sep01&
test_com_check_sep02#INFRASEP02;cpu check sep02||
test_com_check_sep02#INFRASEP02;db check sep02||
test_com_check_sep02#INFRASEP02;disk space check sep02||
How can I concatenate the string as:
"test_com_check_sep01=INFRASEP01;cpu check sep01&INFRASEP01;DBcheck sep01&INFRASEP01;disk space check sep01"
"test_com_check_sep02=INFRASEP02;cpu check sep02||INFRASEP02;db check sep02||INFRASEP02;disk space check sep02"
You could store the values into an array and implode afterwards.
$check = array();
if($result = mysqli_query($link,$query)) {
while($obj = mysqli_fetch_object($result)) {
// If value is not stored in check array proceed
if(!in_array($obj->complex_check_name,$check))
$list[$obj->complex_check_name][] = $obj->complex_check_name."=";
$list[$obj->complex_check_name][] = $obj->server_name.";".$obj->single_check_name.$obj->operator;
// Store in check array
$check[] = $obj->complex_check_name;
}
// Loop through stored rows and implode with break
foreach($list as $array) {
echo implode("<br />",$array);
}
}
try this
$concat1 = '';
$concat2 = '';
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
if($obj->server_name == 'INFRASEP01'){
concat1 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}else{
concat2 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}
}
}
echo $concat1 .'<br>'.$concat2;
Assuming you want to keep the lines separate for use, you could do this
$list = array("INFRASEP01", "INFRASEP01", "INFRASEP02");
$concatINFRASEP01 = "";
$concatINFRASEP02 = "";
for($lineCounter = 0; $lineCounter < sizeof($list); $lineCounter++)
if(strpos($list[$lineCounter], "INFRASEP01") !== false){
//Found it
$concatINFRASEP01 .= " " . $list[$lineCounter];
}
else if(strpos($list[$lineCounter], "INFRASEP02") !== false){
$concatINFRASEP02 .= " " . $list[$lineCounter];
}
NOTE: I did not test this code so there may be errors.
If you do not need the $list array, then you can do as #Malakiof suggested.
EDIT (01/22/2015): I have improved my answer but left the old one there in case I misunderstood.
//In your case the rows come from the $obj (which most would call $row)
$listOfRows = array("test_com_check_sep01#INFRASEP01;cpu check sep01&","test_com_check_sep01#INFRASEP01;DB check sep01&", "test_com_check_sep02#INFRASEP02;cpu check sep02||");
//Create this array as you go through each row by adding the server_name
//to this array. You can skip making this array and simply make the
//unique array by checking if the array contains the server_name.
$listServerNames = array("INFRASEP01","INFRASEP02","INFRASEP01", "INFRASEP02", "INFRASEP01");
//Only have unique server names to avoid duplicates
$listUniqueServerNames = array_unique($listServerNames);
//this will be your list of concatenated strings
$concatByServerName = array();
//Go through the unique server names one by one
foreach($listUniqueServerNames as $serverName)
//While looking at each unique server name, look through the rows
foreach($listOfRows as $line)
if(strpos($line, $serverName) !== false){
//Found it
if(array_key_exists($serverName, $concatByServerName))
$concatByServerName[$serverName] .= " " . $line;
else
$concatByServerName[$serverName] = $line;
}
If the $listOfRows is very large, consider making a copy of $listOfRows and removing the lines from $listOfRows when you add them to $concatByServerName.
Although this is not the best way to do it, I am trying to keep it simple in order for you to be able to get it to work, while fully understanding what is happening. You can easily improve on this code by looking at your project and streamlining these tasks.

Implementing strlen() in a loop

I've got a string here with names of students (leerlingen) and im trying to follow the exercise here.
The code shows the length of the full string.
Next up would be use a loop to check who has the longest name, but how to implement strlen() in a loop?
// change the string into an array using the explode() function
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(" ", $sleerlingen);
echo $namen[0];
echo "<br><br>";
//determin the longest name by using a loop
// ask length
$arraylength = strlen($sleerlingen);
sleerlingen = $i;
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
echo $arraylength;
?>
You used bad separator in your explode function, in string there is no space.
This should work (I didn't try it). In foreach loop you check current length with the longest one and if the current is longer, just save it as longest.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$names = explode(',', $sleerlingen);
$longest;
$longest_length = 0;
foreach ($names as $item) {
if (strlen($item) > $longest_length) {
$longest_length = strlen($item);
$longest = $item;
}
}
echo 'Longest name: ' . $longest . ', ' . $longest_length .' chars.';
?>
You can create a custom sort function to sort the array based on the strings length. Then you can easily take the first key in the array.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(",", $sleerlingen); // changed the space to comma, otherwise it won't create an array of the string.
function sortByLength($a,$b){
return strlen($b)-strlen($a);
}
usort($namen,'sortByLength');
echo $namen[0];
?>

php array, to check if a value at key is set or not and update accordingly

I initialize a php array named $present, the purpose of this array is to hold the value of 1 if a name is present or zero if the name is absent. i have a name array of size 10. below is the code mentioned, but it is not working.
$present = Array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
i have also tried this :
$present = Array();
for($i=0;$i<=10;$i++){
if(empty($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
please help thanks!
I think this may be what you are looking for. You're missing the $i when setting it to 1.
$present = array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
Should be:
$present = Array();
for($i=0;$i<10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
I'm not sure exactly what you're trying to do here, but if you just want to keep track of whether a name is present or not, you could just make $present be an array of names, and then use in_array.
$present = array('John', 'Paul', 'George');
echo in_array('John', $present); # returns 1
echo in_array('MacArthur', $present); #returns 0

Categories