How to convert a string of numbers into an array? - php

I have a string e.g. 1398723242. I am trying to check this string and get the odd numbers out which in this case is 13973.
I am facing problem on how to put this string into an array. After putting the string into an array I know that I have to loop through the array, something like this:
foreach($array as $value){
if($value % 2 !== 0){
echo $value;
}
}
So can any body please help on the first part on "How to put the above string into an array so I can evaluate each digit in the above loop?"

This should work for you:
Just use str_split() to split your string into an array. Then you can use array_filter() to filter the even numbers out. e.g.
<?php
$str = "1398723242";
$filtered = array_filter(str_split($str), function($v){
return $v & 1;
});
echo implode("", $filtered);
?>
output:
13973

Array map is your function (mixed with split)
$array = array_map('intval', str_split($number));
foreach($array as $value){
if($value % 2 !== 0){
echo $value;
}
}

Use str_split() http://www.php.net/manual/en/function.str-split.php
$string = "1398723242";
$array = str_split($string);
foreach($array as $value){
if($value % 2 !== 0){
echo $value;
}
}

if you want string as result, don't convert to array
$str = "1398723242";
echo preg_replace('/0|2|4|6|8/','', $str); //13973
Or, more faster
echo str_replace(array(0,2,4,6,8),'', $str); //13973

You have to know if the string is an array of chars. so you can just iterate it :
<?php
$string = "1398723242";
for($i=0; $i < strlen($string); ++$i){
if($string[$i]=='....'){
$string[$i] = ''; // Just replace the index like this
}
}
?>

$str = '1398723242';
$strlen = strlen($str);// Get length of thr string
$newstr;
for($i=0;$i<$strlen;$i++){ // apply loop to get individual character
if($str[$i]%2==1){ // check for odd numbers and get into a string
$newstr .= $str[$i];
}
}
echo $newstr;

Related

Find the two longest strings separated by dash in PHP

I want to define two new variables as the longest strings from a given string. if the string does not contain any dashes, just choose it for both.
Example:
$orig=`welcome-to-your-world`
$s1=`welcome`
$s2=`world`
$orig=`welcome-to-your-holiday`
$s1=`welcome` // order not important
$s2=`holiday`// order not important
$orig=`welcome`
$s1=`welcome`
$s2=`welcome`
Solution with explode and sorting result array by length of words:
$orig = 'welcome-to-your-world';
$parts = explode('-', $orig);
if (1 < count($parts)) {
usort($parts, function($a, $b) { return strlen($a) < strlen($b); });
$s1 = array_shift($parts);
$s2 = array_shift($parts);
} else {
$s1 = $s2 = $orig;
}
echo $s1 . PHP_EOL . $s2;
Fiddle here.
It seems like your string is in dash-case (words in lower case separated by dashes).
So, you can do the following:
// convert origin in an array
$origin_array = explode("-", $origin);
//retrivies the first element from array
$s1 = '';
$s2 = '';
// get the longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s1)) {
$s1 = $word;
}
}
// remove the longest word from the array
$origin_array = array_diff($origin_array, [$s1]);
// get the second longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s2)) {
$s2 = $word;
}
}
I think that solves your problem. Hope that helps!
Note: This method is not efficient because it runs foreach twice. The other answer is better if you care about performance.
$orig = 'welcome-to-your-world';
$array = explode('-', $orig);
$lengths = array_map('strlen', $array);
$s1key = array_search(max($lengths), $lengths);
$s1 = $array[$s1key];
unset ($array[$s1key], $lengths[$s1key]);
$s2key = array_search(max($lengths), $lengths);
$s2 = $array[$s2key];

How do I reverse a set of comma delimited strings and return them in the original order in PHP? [duplicate]

This question already has answers here:
Reverse the letters in each word of a string
(6 answers)
Closed 1 year ago.
This is the code I have so far. I just started learning PHP today and I'm not sure why my code isn't working.
<?php
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < strlen($str); $x++){
$revStr .= strrev($str[$x]);
}
return $revStr;
}
Any help would be greatly appreciated!
edit: Here is an example input
Php,Arrays,Mysql
here is what i would like the output to be:
phP,syarrA,lqsyM
edit2:
Figured it out. Made a few minor edits. Not sure if it's the most efficient code but it works.
<?php
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < count($str); $x++){
if($x == count($str) - 1){
$revStr .= strrev($str[$x]);
}
else{
$revStr .= strrev($str[$x]) . ",";
}
}
return $revStr;
}
Edit, I see you now included an example.
Use array_map and strrev to reverse the words.
Use explode and Implode to make the words array and back to string.
echo implode(",", array_map(function($part){ return strrev($part);},explode(",", $str)));
https://3v4l.org/tr7d6
I believe you should use array_reverse on the exploded string.
Then you can implode it back to a string.
$str = "apple,orange,tomato";
$arr = explode(",", $str);
$arr =array_reverse($arr);
echo implode(",", $arr); //tomato,orange,apple
https://3v4l.org/Hvd9m
Or, slightly messier but compact:
echo implode(",", array_reverse(explode(",", $str)));
https://3v4l.org/LTu90
You are checking the string length of an array inside of your for loop. Also, a custom function is unnecessary, PHP provides us with strrev().
But if you would like to use your own:
function backwards($input)
{
$str = $input;
$revStr = "";
$str = explode(",",$str);
for($x = 0; $x < count($str); $x++){
$revStr .= strrev($str[$x]);
}
return $revStr;
}
$string = "Php,Arrays,Mysql";
echo backwards($string);
Hope this helps,
You need to use count instead of strlen and also need to take reversed string into array and then convert it into string.
You can try this code :
<?php
function backwards($input)
{
$str = $input;
$revStr = array();
$str = explode(",", $str);
for ($x = 0; $x < count($str); $x++) {
$revStr[] = strrev($str[$x]);
}
return implode(',', $revStr);
}
$str = "Php,Arrays,Mysql";
var_dump(backwards($str));
Just some modification and you got your desired output. You can use explode and implode function of php with array_push to get your result:
<?php
$string = "Php,Arrays,Mysql";
function backwards($input)
{
$str = $input;
$revStr = array();
$str = explode(",", $str);
for ($x = 0; $x < count($str); $x++) {
array_push($revStr, strrev($str[$x]));
}
return implode(',', $revStr);
}
$result =backwards($string);
echo $result;
?>
You can check the demo here
use $str[0] in for loop syntax.
like this => for($x = 0; $x < strlen($str[0]); $x++)

Determine repeat characters in a php string

I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccddd;
I need to determine which character was repeated the most.
So for the above example it would say
The character repeated the most is "B".
However in the example above both B and D are repeated 3 times.
Would need to spot that. B AND D are both repeated 3 times.
This is what I have so far. FAR from what I need but starting point
<?php
$string = "aabbbccddd";
$array=array($array);
foreach (count_chars($string, 1) as $i => $val) {
$count=chr($i);
$array[]= $val.",".$count;
}
print_r($array);
?>
Anyone have any thing that could help me?
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);
Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
use count-chars()
http://php.net/manual/en/function.count-chars.php
and then asort()
http://php.net/manual/en/function.asort.php
<?php
$word = "abcdefghbi";
for($i=0; $i<strlen($word);$i++){
for($k=0;$k<strlen($word);$k++){
if($word[$i] == $word[$k] && $i != $k){
echo $word[$k]." is duplicate";
exit;
}
}
}
echo "no match found";
?>
$data = "aabbbcccdddz";
$array = str_split($data);
$v = array_count_values($array);
foreach($v as $k => $val){
echo $k.' = '.$val.'<br>';
}

Modify numbers inside a string PHP

I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php

Capitalize every other letter within exploded array

Initially i had posted a question to find a solution to capitalize every other letter in a string. Thankfully Alex # SOF was able to offer a great solution, however ive been unable to get it to work with an array... To be clear what im trying to do in this case is explode quotes, capitalize every other letter in the array then implode them back.
if (stripos($data, 'test') !== false) {
$arr = explode('"', $data);
$newStr = '';
foreach($arr as $index => $char) {
$newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
}
$data = implode('"', $arr);
}
Using the anonymous function requires >= PHP 5.3. If not, just make the callback a normal function. You could use create_function(), but it is rather ugly.
$str = '"hello" how you "doing?"';
$str = preg_replace_callback('/"(.+?)"/', function($matches) {
$newStr = '';
foreach(str_split($matches[0]) as $index => $char) {
$newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
}
return $newStr;
}, $str);
var_dump($str);
Output
string(24) ""hElLo" how you "dOiNg?""
CodePad.
If you want to swap the case, swap the strtolower() and strtoupper() calls.
Is this what you're looking for?
foreach($data as $key => $val)
{
if($key%2==0) $data[$key] = strtoupper($data[$key]);
else $data[$key] = strtolower($data[$key]);
}
Or.... instead of using regular expression you could just not even use the explode method, and go with every other character and capitalize it. Here is an example:
$test = "test code here";
$count = strlen($test);
echo "Count = " . $count . '<br/>';
for($i = 0; $i < $count; $i++)
{
if($i % 2 == 0)
{
$test[$i] = strtolower($test[$i]);
}
else
{
$test[$i] = strtoupper($test[$i]);
}
}
echo "Test = " . $test;
The secret lies in the modulus operator. ;)
Edit: Dang, I just noticed the post above me by Jordan Arsenault already submitted this answer... I got stuck on the regex answer I missed that :-/ sorry Jordan, you were already on point.

Categories