I have an array for example
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
Now what I want is to get rid all the same letter from $arr1 to $arr2 and count the remaining.
example output:
oe //total count is 2
You could do something like this,
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
foreach($uniquecounts as $char => $count) {
if($count == 1) {
echo $char . ' is unique' . "\n";
}
}
This combines your two arrays of individualized characters and compares them for only one occurrence of the character. Take a look at the manual for how to use array_count_values, http://php.net/manual/en/function.array-count-values.php, in the future.
Output:
o is unique
e is unique
Update:
<?php
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
$unqiues = '';
foreach($uniquecounts as $char => $count) {
if($count == 1) {
$unqiues .= $char;
}
}
echo $unqiues . ' ' . strlen($unqiues);
Output:
oe 2
function deduce($string1, $string2) {
$result = array();
foreach (count_chars($string2 . $string1, 1) as $i => $val) {
if($val == 1) {
$result[] = chr($i);
}
}
return $result;
}
I've encountered this one before and what I did was this.
Related
I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.
Example :
Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
This what I could achieve so far:
$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
So, it is very short version
function check($string,$count = 1) {
$achives = [];
$strArray = count_chars($string, 1);
array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
$cnt!==$count?:$achives[chr($letter)] = $cnt;
});
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));
But it is exactly answer for your question:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = str_split($string, 1);
foreach($strArray as $index => $char ){
$strings[$char] = isset($strings[$char])?++$strings[$char]:1;
}
if($count) {
foreach($strings as $char => $cnt) {
if($cnt==$count) {
$achives[$char] = $cnt;
}
}
}
return $achives;
}
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
You can simply do this with php str_split() and array_count_values() built in functions. i.e.
$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
foreach ($letterCountArray as $key => $value) {
echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}
Output
I have N array
$array[1] = array("a","b","c");
$array[2] = array("p","q","r");
In a string if i found any word in any array then it should get replaced with any other word of the same array
Example
$text="a d r";
then replace "a" with any other value of $array[1] and "r" with any other value of $array[2]
How can i do it in PHP ?
$total=count($a);
for($i=0;$i<$total;$i=$i+1)
{
$subtotal=count($a[$i]);
for($j=0;$j<$subtotal;$j=$j+1)
{
if(strpos($text,$a[$i][$j]) !== false)
{
for($k=0;$k<$subtotal;$k=$k+1)
{
if($a[$i][$j]!=$a[$i][$k])
{
$text=str_replace($a[$i][$j],"<font color='red'>".$a[$i][$k]."</font>",$text);
break;
}
}
break;
}
}
}
You can use something like this
$array[1] = array("a","b","c");
$array[2] = array("p","q","r");
$text="adr";
$finaloutput = '';
foreach(str_split($text) as $val){
if(in_array($val,$array[1])){
$k = array_rand($array[1]);
$v = $array[1][$k];
}
elseif(in_array($val,$array[2])){
$k = array_rand($array[1]);
$v = $array[1][$k];
}
else{
$v = $val;
}
$finaloutput .= $v;
}
echo $finaloutput;
This question already has answers here:
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 7 years ago.
My php output is an array. Like:
$array = array('banana', 'mango', 'apple');
Now If output is only 'Banana' then it will show simply
Banana
If output is 'banana' & 'mango' or 'apple' the i want to show like
Banana or Mango
If output is all.. then result will be shown
Banana, Mango or Apple
Now I can show result with comma using this code
echo implode(",<br/>", $array);
But How to add or ??
Please help.
Try this:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
use the count and map with that like
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
you can replace last occurrence of a string in php by this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
please try below Code :
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;
$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
I want to check if $value contains any of the values of the $search array. I can find out using foreach and the strpos function. Without resorting to using foreach, can I still find the answer? If so, kindly help me to solve this problem.
Explode $value and convert it into array and then use array_intersect() function in php to check if the string does not contain the value of the array.Use the code below
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
Test the code here http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
Hope this helps you
Yes, but it will require you to re structure your code.
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}
Use array_map() and array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);
$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}
Here's a solution using array_reduce:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>
My first inclination was to solve the problem with array_walk() and a callback, as follows:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
Live demo: http://3v4l.org/6B0WX
While this solves the problem without a foreach loop, it answers the question with a "what" rather than a "yes/no" response. The following code directly answers the question and permits answering the "what" too, as follows:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
Live demo: http://3v4l.org/WJQ5c
If the response had been negative, then the output is 'No.' followed by a blank space.
A key difference in this second solution compared to the first, is that in this case there is a return result that can be manipulated. If an element of the array matches a character in the string, then array_filter adds that element to $chars. The new array's element count answers the question and the array itself contains any matches, if one wishes to display them.
I am trying to output any array to a directory list format.
A-Z is working, but I want to output words that don't begin with A-Z to the symbol #.
E.G. 1234, #qwerty, !qwerty, etc should be sorted to the # group.
<?php
$aTest = array('apple', 'pineapple', 'banana', 'kiwi', 'pear', 'strawberry', '1234', '#qwerty', '!qwerty');
$range = range('A','Z');
$range[] = "#";
$output = array();
foreach($range AS $letters){
foreach($aTest AS $fruit){
if(ucfirst($fruit[0]) == $letters){
$output[$letters][] = ucfirst($fruit);
}
}
}
foreach($output AS $letter => $fruits){
echo $letter . "<br/>--------<br/>\n";
sort($fruits);
foreach($fruits AS $indFruit){
echo $indFruit . "<br/>\n";
}
echo "<br/>\n";
}
?>
$output['#'] = array();
foreach($range as $letter){
$output[$letter] = array();
}
foreach($aTest AS $fruit){
$uc = ucfirst($fruit);
if(array_search($uc[0], $range) === FALSE){
$output['#'][] = $uc;
} else {
$output[$uc[0]][] = $uc;
}
}
notice that I have removed outer loop, as you don't need it
You should reverse the order of the two foreach loops, use break and a temporary variable:
foreach($aTest as $fruit){
$temp = 1;
foreach($range as $letters){
if(ucfirst($fruit[0]) == $letters){
$output[$letters][] = ucfirst($fruit);
$temp = 0;
break;
}
}
if($temp){
$output["#"][] = $fruit;
}
}
ksort($output);
To avoid these complications, you may use only one foreach loop and the built-in PHP function in_array:
foreach($aTest as $fruit){
$first = ucfirst($fruit[0]);
if(in_array($first, $range)){
$output[$first][] = ucfirst($fruit);
}
else{
$output["#"][] = $fruit;
}
}
ksort($output);
I would categorize them first using ctype_alpha() and then sorting the result by the array key:
$output = array();
foreach ($aTest as $word) {
$output[ctype_alpha($word[0]) ? strtoupper($word[0]) : '#'][] = $word;
}
ksort($output);