Example : string="abc,def,rst,xyz"
Output Should be 4
Is there a function that will count the number of values inside a concatenated string without the need for looping.
Thanks
You could use explode which creates an array with the comma as delimeter. No looping needed here.
$string = "abc,def,rst,xyz";
$ex = explode(",",$string);
$amount = count($ex);
//Will return 4
echo $amount;
If you always have a string like abc,def,rst,xyz, you could do something like :
echo substr_count('abc,def,rst,xyz', ',') + 1;
Of course, this is assuming you have a well-formatted string. It won't work with strings like :
'abc,def,rst,'
',def,rst,xyz'
'abc,,rst,xyz'
// And so on...
Try with
$count = substr_count($yourString, ',') + 1;
You are looking for substr_count()
Use it like: $count = substr_count($myString, ",")+1;
But couldn't the strings themselves contain a comma?
You should probably look into the csv functions, such as: str_getcsv() and then do count() on it.
Related
I have a string that looks like this
$genres = "pop,rock,jazz,80s";
i was wondering is it possible to then create a string that randomly selects any of those genres above? but removing the comma?
for example it would create
$newgenre = "pop";
You could use something like this:
$genreArray = explode(',', $genres);
$genre = $genreArray[mt_rand(0, count($genreArray))];
Alternative Method
Everyone else is using random selection from an array, try this alternative:
$genreArray = explode(',', $genres);
shuffle($genreArray); //mixes up the array using rand or mt_rand
$genre = $genreArray[0]; // take first element of shuffled array.
You can use the $genreArray = explode(',', $genres) function to put it all into an array.
Then you can generate a random index for the array, using
$randomKey = rand(0, count($genreArray))
And then, all you have to do is take the random genre from the array.
$randomGenre = $genreArray[$randomKey];
You could explode
and get a random value from the array
$genresArray = explode(',',$genres);
$your_values = array_rand ($genresArray,1);
echo $your_values[0];
I have variables of form like:
$x = "1-15"
$y = "2-18"
etc.
I need to extract the first and second integer as separate variables.
For example:
if $x = "1-15", return values should be $z = 1 and $w = 15.
I know that It would be possible to do this with regex, but from what I've heard, it should be avoided if possible.
What then would be the "fastest" way of achieving this?
If you are sure this is the format, you can split the string (assuming it is a string, and not literally what you wrote).
Splitting is done with explode in php:
http://php.net/manual/en/function.explode.php
$x = "1-15"; //assuming it is indeed a string
list($z, $w) = explode('-', $x);
Using explode is a better option, If you want to go with regex, Hope this solution will be okay.
Regex: ^\s*(\d+)\s*\-\s*(\d+)\s*$
1. ^\s*(\d+)\s*\-\s*(\d+)\s*$ This will match digits - digits pattern, this will take care of spaces as well.
Try this code snippet here
<?php
$x = '1-15';
extract(getVariables($x));
echo $z;
echo $w;
function getVariables($x)
{
preg_match("/^\s*(\d+)\s*\-\s*(\d+)\s*$/", $x,$matches);
return array("z"=>$matches[1],"w"=>$matches[2]);
}
Let's say I have the following url: example.php?grab=1,3&something=...
grab has two values, how can I translate that to a conditional if statement.
For example, if count is a variable and you want to calculate if count is equal to one of the grab values.
$grab = $_GET["grab"];
$count = 4;
if($count == $grab(values)) {
alert("True");
}
If its always going to be , that glues the values, just explode them, that turns them into an array. Then just use your resident array functions to check. In this example, in_array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
$pieces = explode(',', $grab);
if(in_array($count, $pieces)) {
// do something here if found
}
}
Sidenote: If you try to devise your url to be like this:
example.php?grab[]=1&grab[]=3&something
You wouldn't need to explode it at all. You can just get the values, and straight up use in_array.
The example above grab already returns it an array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
if(in_array($count, $grab)) {
// do something here if found
}
}
Method#1: Reformat URL and Use PHP in_array()
Why not reformat your url to something like this: example.php?grab[]=1&grab[]=3&something=... which automatically returns the grab value as an array in PHP?
And then do something like:
if(isset($_GET['grab']) && in_array(4, $_GET['grab'])) {
// do something
}
Method#2: Split String into Array and Use PHP in_array()
If you do not wish to reformat your url, then simply split the string into an array using php's explode function and check if value exists, for example:
if(isset($_GET['grab'])) {
$grab_array = explode(",", $_GET['grab'])
if(in_array(4, $grab_array)) {
// do something
}
}
Method#3: Use Regular Expressions
You could also use regular expressions to check for a match.
I'm fairly new at php, but this seems to be me overlooking something completely basic?
I have some values in a database column, that are comma separated like so:
1,2,3
When I try to get the sum of the values, I expect the echo of array_sum to be 6, but I only get returned the first value ie. "1"
echo $amount; //Gives 1,2,3 etc.
$amount_array = array($amount);
echo array_sum($amount_array); //Only prints "1"
print_r($amount); // shows 1,2,3
print_r($amount_array); // shows Array ( [0] => 1,2,3 )
It's a string not an array, you have to split it using explode function:
$exploded = explode ( "," , $amount_array);
var_dump($exploded);
To use the array_sum the string needs to be converted to an array
You need to use the explode function:
$amount_array = explode(',', $amount);
So you total code should be like this:
$amount_array = explode(',', $amount);
echo array_sum($amount_array);
array_sum() works by adding up the values in an array. You only have one key=>value pair in your array: key 0 with a value of 1,2,3.
If you have a comma-separated list, and want that to be an array, I would use the explode() function to turn the list into the proper key=>value pairs that array_sum() would expect.
Try
$amount_array = explode(',',$amount);
You can not initialize an array the way you intend. You are passing in a comma-separated string, which is just a single argument. PHP doesn't automagically convert that string into separate arguments for you.
In order to convert a comma-separated string into an array of individual values you can break up the string with a function like explode(), which takes a delimiter and a string as its arguments, and returns an array of the delimiter-separated values.
$amount_array = explode( ',', $amount ); // now $amount_array is the array you intended
I have a SQL query which returns a result of one field, so I have the following:
$article_id = $this->item->id;
$authors_default = mysql_query("SELECT multi_authors FROM jos_jxzine_articles WHERE id = '$article_id' LIMIT 1");
$authors_default = mysql_fetch_assoc($authors_default);
echo $authors_default['multi_authors'];
This echos out
128,129
and so on for different queries.
How can I make this into the following
array(128,129)
To then put into a prewritten function?
Cheers
The following code takes that MySQL row and splits it up into pieces using , as the delimiter. It then converts that array of strings to an array of integers.
$authors_arr = explode(',', $authors_default['multi_authors']);
// $authors_arr = array("128", "129");
$authors_arr = array_map('intval', $authors_arr);
// $authors_arr = array(128, 129);
You can then pass that array into a function like so:
myFunction($authors_arr); // Or however you have it setup.
$authors_array = explode(",", $authors_default['multi_authors']);
This will break apart your MySQL result into an array. Since your query pulls a string which is delimited by a comma, the explode() function can be used to separate out the string.
http://php.net/manual/en/function.explode.php
Sorry, this is untested since I have removed PHP from my localhost. If I understand you correctly.
<?php $arr = explode(',', $authors_default['multi_authors']); print_r($arr); ?>
http://php.net/manual/en/function.explode.php