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);
Related
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.
Suppose I have the following table information
+-------------+---------------+
+ id + letters +
+-------------+---------------+
+ 1 + a, b, c, d, e +
+-------------+---------------+
I am trying to capture the values of the column and store them in variables:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
$letter1 = ** what comes here? **;
$letter2 = ** what comes here? **;
}
You can try this way:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
$letters = explode(',',mysql_fetch_array($result));
Now you can access any letter using an array, like this $letters[0]; //a.
Instead of having
$letter1
$letter2
I would make an' array with explode.
$letter = explode(',', $data['letters']);
That way you can acccess your letters with a simple $letter[0] or $letter[1]
Now the above code works from the assumption that you only run through the while loop ONCE.
If you run through the while loop more than once, I'd do it like this:
$letter[] = explode(',', $data['letters']);
which is accessed by $letter[0][0] - The first [] being the instance of number when it was fetched, the second [] being the letter you want to fetch.
Another thing
Mysql is outdated / not gonna be used / very unsecure so I would advice you to find another alternative to mysql, such as mysqli or PDO - It is better to use these while you are learning because that way you avoid getting stuck with bad routines.
How about this?
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
/* list($letter1,$letter2,$letter3,$letter4,$letter5) = explode(',' , $data['letters']);
*/
$letters = array();
// letters array will have the exploded letters
$letters = explode(',' , $data['letters']);
}
Your question is unclear. Please provide more details for a better answer :)
My query generates a result set of UID values which looks like:
855FM21
855FM22
etc
I want to isolate the last number from the UID which it can be done by splitting the string.
How to split this string after the substring "FM"?
To split this string after the sub string "FM", use explode with delimiter as FM. Do like
$uid = "855FM22";
$split = explode("FM",$uid);
var_dump($split[1]);
You can use the explode() method.
<?php
$UID = "855FM21";
$stringParts = explode("FM", $UID);
$firstPart = $stringParts[0]; // 855
$secondPart = $stringParts[1]; // 21
?>
use explode function it returns array. to get the last index use echo $array[count($array) - 1];
<?php
$str = "123FM23";
$array = explode("FM",$str);
echo $array[count($array) - 1];
?>
For it,please use the explode function of php.
$UID = "855FM21";
$splitToArray = explode("FM",$UID);
print_r($splitToArray[1]);
Have you tried the explode function of php?
http://php.net/manual/en/function.explode.php
As a matter of best practice, never ask for more from your mysql query than you actually intend to use. The act of splitting the uid can be done in the query itself -- and that's where I'd probably do it.
SELECT SUBSTRING_INDEX(uid, 'FM', -1) AS last_number FROM `your_tablename`
If you need to explode, then be practice would indicate that the third parameter of explode() should set to 2. This way, the function doesn't waste any extra effort looking for more occurrences of FM.
echo explode('FM', $uid, 2)[1]; // 21
If you want to use php to isolate the trailing number in the uid, but don't want explode() for some reason, here are some wackier / less efficient techniques:
$uid = '855FM21';
echo strtok($uid, 'FM') ? strtok('FM') : ''; // 21
echo preg_replace('~.*FM~', '', $uid); // 21
echo ltrim(ltrim($uid, '0..9'), 'MF'); // 21
$uid = '123FM456';
$ArrUid = split( $uid, 'FM' );
if( count( $ArrUid ) > 1 ){
//is_numeric check ?!
$lastNumbers = $ArrUid[1];
}
else{
//no more numbers after FM
}
You can also use regular expressions to extract the last numbers!
a simple example
$uid = '1234FM56';
preg_match( '/[0-9]+fm([0-9]+)/i', $uid, $arr );
print_r($arr); //the number is on index 1 in $arr -> $arr[1]
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.
I want join array elements with a string (ex:-), i tried it with implode, but it don't work in my code.
How can fix it?
PHP:
<?php
$count = 1;
$ttttt = json_decode('["110,2"]');
$nnnnn = array("110","1","2");
$fffff = array('name','day','last');
$Rtp = str_replace($nnnnn, $fffff, $ttttt, $count);
echo implode(" - ", $Rtp); // This output is as: name,last
?>
DEMO: http://codepad.viper-7.com/ZNiBWy
You JSON is not valid the way you are expecting it, it generates only one value 110,2.
Change it to ["110","2"] and your implode should be ok.
You have an array $ttttt = array(110, 2) .
You then replace all values in this array as follows 110 -> name, 2 -> last and 1 -> day, using str_replace.
So (110, 2) becomes ("name", "last")