Removing beginning and end character from String without altering array - php

I'm running a query to display an array. After the array is displayed I'm using that in Google Maps so the array needs to read a specific way.
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
So my array has to read array', 'array', 'array because I echo the array into the address.
var addresses = ['<?php echo $namelist ?>'];
This is my code and it outputs 'array', 'array', 'array',
$resultsearch = $con->query("SELECT * FROM db") or die(mysqli_error());
$name = array();
while ($result = $resultsearch->fetch_object()) {
$name[] = $result->name;
$namelist = substr("'".implode($name)."', ", 0, -1);
If I change the 0, -1 to 1, -2 then I'm left with array' array' array' and so forth.
I literally need the remove 1 character from the end of string and 1 character at the beginning without altering the characters of the array.
Just to add that using implode(',', $name); did not display the ',' which is why I'm trying to find a work around.
Any ideas?

Your problems are:
You use implode(); in the wrong way: right is implode("', '",$names);
substr() will not work because of wrong use of implode().
Tip: Instead of using substr() just do rtrim('value',',');
To fix your code change it to this:
$name[] = "'{$result->name}'";
$namelist = implode(', ',$name);
or this
$name[] = $result->name;
$namelist = implode("', '",$name);
And this too:
var addresses = [<?php echo $namelist ?>];
to get proper javascript/json array data.
Also works:
var addresses = <?php echo json_encode($namelist); ?>;
But here you should not add ' single-quotes to the names when collecting into an array.
Have a nice day

I ended up with $namelist = "'".$result->name."'," and then echo $namelist;
My results were addresses and believe that implode(',', $name) wouldn't work because of the results.

Related

Remove comma From the last value in a While loop

My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);

Compare two strings and generate a new string with components from both

I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!

Grabbing array from database, then getting information using each array value

totally stumped in this, basically I'm getting a comma seperated list from a user table, using it as an array and then using each value in the array to fetch data from a different table and output then.
$award_array = array($user_class->awards);
foreach($award_array as $award) {
$getaward = mysql_query("SELECT `name`, `text`, `image` FROM `awards_av` WHERE `id` = '".$award."'");
$awardstuff = mysql_fetch_array($getaward);
echo "<img src='".$awardstuff['image']."' alt='".$awardstuff['name']."' title='".$awardstuff['text']."' />";
}
This is only giving out the first number in the array ($user_class->awards in this case is 1,2,3,4,5,6)
Any help is much appreciated!
I think I see the problem. You cannot simply take a string of a comma separated list, and throw it inside an array() tag and expect it to automatically convert it to an array. You must use the explode() function to do that.
What you're trying to do:
<?php
$string = 'a,b,c,d,e';
$myarray = array($string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
Except that doesn't work. You need to convert the comma-separated list of values (which is a string) into an array, but you don't use array() to do that. You use PHP's built-in function called explode() -> http://php.net/explode like this...
<?php
$string = 'a,b,c,d,e';
$myarray = explode(',' $string);
foreach ($myarray as $k => $v) {
print $v .'<br />';
}
?>
I think that is the problem you're having

Remove trailing comma from line of text generated by final iteration of loop

I am creating lines of text to be consumed by another layer in my application. The lines are:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027],
What is the fastest/easiest way to remove the trailing comma from the last line of text?
I'm expecting something like this:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027]
Actual Code:
$i = 0;
while($graph_data = $con->db_fetch_array($graph_data_rs))
{
$year = $graph_data['year'];
$month = $graph_data['month'];
$count = $graph_data['count'];
$total_count = $graph_data['total_count'];
// for get last 2 digits of year
$shortYear = substr($year, -2, 2);
// for get month name in Jan,Feb format
$timestamp = mktime(0, 0, 0, $month, 1);
$monthName = date('M', $timestamp );
$data1 = "['".$monthName.' '.$shortYear."',".$total_count."],";
$i++;
}
If you have that array in a variable and want a string, you can use implode to get a string separated by a glue char.
If you already have an string, you can use rtrim to remove the last char to the right of the string.
If you have an array, where the value is a string ['Oct 13',1027] (ending in a comma), you have the same options above and:
You can use array_walk with some of the mentioned functions
You can get the last element, and use rtrim on it like the code below:
Example of code using rtrim on a array of strings:
<?php
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$lastIndex = count($values)-1;
$lastValue = $values[$lastIndex];
$values[$lastIndex] = rtrim($lastValue, ',');
<?php
$arr = array(
"['Jun 13',529],",
"['Jul 13',550],"
);
$arr[] = rtrim(array_pop($arr), ', \t\n\r');
print_r($arr);
// output:
// Array
// (
// [0] => ['Jun 13',529],
// [1] => ['Jul 13',550]
// )
Make it an actual array, and implode. Not really sure what is is going to be (if json:you can do even better and not make the values themselves fake-arrays, but this is left as an exersize to the reader).
$yourData = array();
while(yourloop){
//probaby something like: $yourData = array($monthName=>$total_count);
$yourData[] = "['".$monthName.' '.$shortYear."',".$total_count."]";
}
//now you have an actual array with that data, instead of a fake-array that's a string.
//recreate your array like so:
$data1 = implode(','$yourData);
//or use json_encode.
Something similar to #srain but using array_push.
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$last = array_pop($values); //pop last element
array_push( $values, rtrim($last, ',') ); //push it by removing comma
var_dump($values);
//output
/*
array
0 => string '['Oct 13',1027],' (length=16)
1 => string '['Oct 13',1027]' (length=15)
*/
#ElonThan was right and so was #BenFortune. This is an XY Problem, and none of the other answers are giving you the best advice -- "Never craft your own json string manually".
You think you just need to remove the final comma from your textual output so that it creates something that javascript can parse as an indexed array of indexed arrays.
What you should be doing is creating a multidimensional array then converting that data into a json string. PHP has a native function that does exactly this AND it guarantees that you will have a valid json string (because it will escape characters as needed).
I'll demonstrate how to adjust your script based on your while() loop.
$result = [];
while ($row = $con->db_fetch_array($graph_data_rs)) {
$result[] = [
date('M y', strtotime($row['year'] . '-' . $row['month'])),
$row['total_count']
];
}
echo json_encode($result, JSON_PRETTY_PRINT);
Here is an online demo that re-creates your query's result set as an input array, then replicates the loop and result generation. https://3v4l.org/cG66l
Then all you have to do is echo that string into your rendered html document's javascript where required.

php exploded associative array problem

I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"]; is working well, but echo $array["Peter"]; is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
You'll have to go in two steps :
First, explode using ', ', as a separator ; to get pieces of data such as "Peter"=>32
And, then, for each value, explode using '=>' as a separator, to split the name and the age
Removing the double-quotes arround the name, of course.
For example, you could use something like this :
$result = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(', ', $ages2) as $couple) {
list ($name, $age) = explode('=>', $couple);
$name = trim($name, '"');
$result[$name] = $age;
}
var_dump($result);
And, dumping the array, you'd get the following output :
array
'Peter' => string '32' (length=2)
'Quagmire' => string '30' (length=2)
'Joe' => string '34' (length=2)
Which means that using this :
echo $result['Peter'];
Would get you :
32
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
$array = eval('return array('.$ages2.');');
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
You'll need to build the array yourself by extracting the name and age:
<?php
$array = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(",", $ages2) as $element) {
$parts = explode("=>", $element);
if (count($parts) == 2) {
$name = str_replace(array('"', ' '), '', $parts[0]);
$age = (int) $parts[1];
$array[$name] = $age;
}
}
print_r($array);
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$items = explode(",", $ages2);
foreach ($items as $item) {
list($key,$value) = explode('=>',$item);
$key = str_replace('"','',trim($key)); // Remove quotes and trim whitespace.
$array[$key] = (int)$value;
}
If you var_dump($array), you'll have:
array(3) {
["Peter"]=>
int(32)
["Quagmire"]=>
int(30)
["Joe"]=>
int(34)
}
So you can do this as expected and get 32 back out:
echo $array['Peter']

Categories