Implodes remove double quotes - php

$view_array = implode(',', $view_array);
When I var_dump this the value is "3,1" how can I remove the outer quotes so it will become 3,1 only

The quotes are part of the way you are outputting it. They don't exist, there is no spoon. Use echo instead...
$view_array = [1,2,3];
$view_array = implode(',', $view_array);
echo $view_array;
Outputs
1,2,3

Well you can use explode, and just use the value by itself:
$view_array = explode(',', $view_array);
echo $view_array[0];
Or put it in a loop and render them all
$view_array = explode(',', $view_array);
for ($i=0; $i < count($view_array) ; $i++) {
# code...
echo $view_array[$i];
}

Related

How to apply double quotes to each value in a comma-space delimited string?

I want to add double quotes of my every array.
Original value is:
192.168.183.2, 192.168.183.28
The current result is:
"192.168.183.2, 192.168.183.28"
What I want is:
"192.168.183.2", "192.168.183.28"
and here is my code:
$allowedIP = array($dScheduler['ALLOWED_IP_ADDRESS']);
echo $newarray='"'.implode('","', $allowedIP).'"';
Your input value is a string, so handle it with just one string function call (str_replace()):
Code: (Demo)
$dScheduler['ALLOWED_IP_ADDRESS']='192.168.183.2, 192.168.183.28'; // your input string
$wrapped='"'.str_replace(', ','", "',$dScheduler['ALLOWED_IP_ADDRESS']).'"';
echo $wrapped;
echo "\n\n";
// if you want an array:
$array=explode(', ',$wrapped); // generate result array
foreach($array as $v){
echo "$v\n";
}
The value delimiter in your input string is: ,, so you just need to change it to ", " and wrap the entire string in " as well.
Then you simply explode on the commas to generate your desired array of elements.
Output:
"192.168.183.2", "192.168.183.28"
"192.168.183.2"
"192.168.183.28"
Do it through a loop:
$new_array = array();
foreach($array as $a) {
$new_array[] = '"'.$a.'"';
}
It will create a new array with ", around each element.
You can use array_map
<?php
$allowedIP = array('192.168.183.2, 192.168.183.28');
$arrAllowedIP = explode(',', $allowedIP[0]);
$quotedIP = array_map(function($val)
{
return '"'.trim($val).'"';
}, $arrAllowedIP);
Try This,
$arr = ["192.168.183.2", "192.168.183.28"];
$imp = '"'.implode('", "', $arr).'"'; // to string with double quote
$exp = explode(',', $imp); // to array with double quote
echo $im;
print_r($exp);
$allowedIP = array('192.168.183.2, 192.168.183.28');
$new= implode($allowedIP);
$fl=',';
foreach (explode(',',$new) as $v){
echo '"'.$v.'"'.$fl;
$fl='';
};

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

How to truncate a delimited string in PHP?

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

Access json result with spaces

I am getting a json result from an API. One of the keys in presented in a question, rather than a true key like this:
{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}
"Question Here about something. There are also quotes like this \"here\""
Will always remain the same, but how to I access its value (thevalue).
I'm trying something like:
$result = json_decode($jsonresult);
echo $result->questions->Question Here about something. There are also quotes like this \"here\");
But that does not work because of the spaces and escaped quotes. Any suggestions?
Try Below:
$jsonresult = '{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}';
$result = json_decode($jsonresult);
echo $result->questions[0]->{'Question Here about something. There are also quotes like this "here")';
This will result thevalue
A much easier way is to just convert the JSON string into a PHP associative array like this:
$json_string = '{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}';
$json = json_decode($json_string, true);
$questions = $json['questions'];
for($i = 0; $i < count($questions); $i++) {
$question = $questions[$i];
foreach($question as $key => $value) {
echo "Question: " . $key . "\n";
echo "Answer:" . $value . "\n";
}
}

php reading in strings from text area

$data = explode("\n", trim($_GET['names']));
while($i < count($data)) {
if(!in_array($data[$i], $unique_names)){
$unique_names[] = $names[$i];
}
$i = $i + 1;
}
I am trying to accept only unique results from a textarea using this php code. It is not working because every string has an extra blank space, except for the last one.
I.E.
"jeff "
"fred "
"bill "
"jeff"
so jeff will be added twice.
My question is:
How Do I get rid of that space?? I tried trim and it won't perform as intended.
First of all, you don't need to find unique values manually, you can use array_unique(). Secondly, trim() doesn't work on arrays.
Try:
$raw_names = explode("\n", $_GET['names']);
$trimmed_names = array_map('trim', $raw_names);
$unique_names = array_unique($trimmed_names);
Use trim(string) to remove whitespace from the start and end. http://php.net/manual/en/function.trim.php
Inspired by kba :
$data = explode("\n", trim($_GET['names']));
foreach ($data as &$e) {
$e = trim($e);
}
$unique_names = array_unique($data);

Categories