Can someone please give me a hand making this explode function recursive? My head is not working today.
function expl($str,$charlist='|'){
$charlist = str_split($charlist);
foreach($charlist as $char){
if(is_array($str)){
for($i=0; $i<sizeof($str); $i++){
$str[$i] = expl($str[$i],$char);
}
}else{
return (explode($char,trim($str,$char)));
}
}
return($str);
}
echo "<pre>";
print_r(expl("A~a1~a2|B~b1~b2",'|~'));
echo "</pre>";
Should output:
Array
(
[0] => Array
(
[0] => A
[1] => a1
[2] => a2
)
[0] => Array
(
[0] => B
[1] => b1
[2] => b2
)
)
<?php
function expl($str, $charlist = '|')
{
if (!$charlist) {
return $str;
}
$char = $charlist[0];
$matrix = explode($char, $str);
for ($i = 0; $i < sizeof($matrix); $i++) {
$matrix[$i] = expl($matrix[$i], substr($charlist, 1));
}
return $matrix;
}
echo "<pre>";
print_r(expl("A~a1~a2|B~b1~b2", '|~'));
echo "</pre>";
that would be something like this...
use recursion!
the first level will get the first matrix, doing something like this
$matrix[0] = "A~a1~a2";
$matrix[1] = "B~b1~b2";
and then, the recursion will do the second part, which will make each string become the array of strings, that will become the array of strings until there's no more separators.
The below is a working example, and I've provided a link to show you the output when the function is run:
Example return:
http://phpfiddle.org/api/run/4iz-i2x
Usage:
echo '<pre>';
print_r( expl("A~a1~a2|B~b1~b2",'|~'));
echo '</pre>';
Function:
<?php
function expl($str,$charlist='|', $currentChar = 0, $continue = true){
if(!$continue)
{
return $str;
}
$endArray = array();
if($currentChar == 0){
$charlist = str_split($charlist);
}
else
{
if($currentChar > count($charlist))
{
return expl($str, $charlist, $currentChar, false);
}
}
if(!is_array($str))
{
$pieces = explode($charlist[$currentChar], $str);
$currentChar++;
return expl($pieces, $charlist, $currentChar);
}
else{
foreach($str as $arrayItem){
if(is_array($arrayItem))
{
return expl($str, $charlist, $currentChar, false);
}
$endArray[] = explode($charlist[$currentChar], $arrayItem);
}
$currentChar++;
return expl($endArray, $charlist, $currentChar);
}
}
?>
Simply do like this.First explode by '|' then by '~'. it should be something like this:
$str="A~a1~a2|B~b1~b2";
$arr=explode("|",$str);
$result=array();
foreach($arr as $k=>$v)
{
$arr1=explode("~",$v);
$result[]=$arr1;
}
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
Example string: "outofthebox"
I want to get output like this: Array ( [0] => out [1] => of [2] => the [3] => box )
What do I get right now: Array ( [0] => out [1] => oft [2] => heb [3] => ox )
I don't know how it's possible. I need that logic, how can I get more meaningful results.
I'm building it on PHP based on this https://stackoverflow.com/a/481773/17035224 Python answer. But I'm not good at Python. In this python script it's returning results like exactly what I want. Another script in python called 'wordninja' is working great too.
My PHP script:
<?php
$db = new PDO("mysql:host=localhost;dbname=strings", "root", "");
$text = "outofthebox";
$finish = false;
$words = [];
$find = false;
$start = -1;
$added = false;
$comp = [];
for($i = 0; $i<strlen($text); $i++) {
if(count($words) > 0) {
$last = max($words);
$comp[] = $last;
$words = [];
$start = strlen(implode("", $comp));
if($added === true) {
$added = false;
}else {
$start++;
}
}else {
$start++;
}
$part = "";
for($j = $start; $j<strlen($text); $j++) {
$part .= $text[$j];
echo $part."<br>";
$check = checkWord($part);
if($check === true) {
$added = true;
$words[] = $part;
}
}
}
print_r($comp);
function checkWord($text) {
global $db;
$check = $db->query("select * from strings where string='".$text."'")->fetch(PDO::FETCH_ASSOC);
if(isset($check["id"]) == true) {
return true;
}
return false;
}
Other difference is as you see I'm using mysql database for dictionary instead of txt.
If you change the checkWord function to this :
function checkWord($text) {
$arr = [
'out',
'of',
'the',
'box',
];
if(in_array($text, $arr)) {
return true;
}
return false;
}
You will see that the result will be :
Array ( [0] => out [1] => of [2] => the [3] => box )
So my guess is that you have false-positives coming from your query, check that and you'll solve the problem.
I have some array like this how can i split the key and value in php ?
[A0E4NL014XVM273] => Array
(
[0] => qexixdb
)
[A0E4UK024XVM014_Clone] => Array
(
[0] => pe8w3100
[1] => pe8w3100
)
Tried Query
foreach($vm_array as $vmkey=> $vmvalue){
$varray[] = $vmvalue;
/*foreach($vmvalue as $vmvalue=> $vmvalufmarray){
$vm_array[$vmkey][] = $vmvalufmarray.',';
}*/
}
Expected Output
[A0E4UK024XVM014_Clone] => pe8w3100,pe8w3100
You need to make a function called implode().
foreach($vm_array as $vmkey=> $vmvalue){
$varray[$vmkey] = implode(",", $vmvalue);
}
print_r($varray);
Try using PHP's implode on the inner array;
foreach($vm_array as $vmkey => $vmvalue){
$vm_array[$vmkey] = implode(",", $vmvalue);
}
I tried your example and simulated my own, if my understanding is right, if you want to retain them in the array.
$test = array("[A0E4NL014XVM273]" => array("qexixdb"),"[A0E4UK024XVM014_Clone]" => array("pe8w3100","pe8w3100"));
echo "<pre>";
var_dump($test);
echo "</pre>";
$new_arr_ = array();
foreach($test as $id => $value) {
$new_val = "";
for($i = 0, $ctr_val = count($value); $i < $ctr_val; $i++) {
$old_id = "";
if($id != $old_id) {
if($i < ($ctr_val - 1)) {
$new_val .= $value[$i] . ",";
} else {
$new_val .= $value[$i];
}
$old_id = $id;
}
}
$new_arr_[] = array($id => $new_val);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Or if just one array:
$new_arr_ = array();
foreach($test as $key=> $value){
$new_arr_[key] = implode(",", $value);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Hope it helps.
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.
I have the following array:
Array
(
[0] =>
[1] =>
[2] => apple
[3] =>
[4] => orange
[5] => strawberry
[6] =>
)
How can I remove the empty items from the beginning and the end, but not from the inside? The final array should look like this:
Array
(
[0] => apple
[1] =>
[2] => orange
[3] => strawberry
)
Here's a convenient way:
while (reset($array) == '') array_shift($array);
while (end($array) == '') array_pop($array);
See it in action.
Obligatory comment: I 'm using a loose comparison with the empty string because it looks like what you intend given your example. If you want to be more picky about exactly which elements to remove then please customize the condition accordingly.
Update: bonus hallmark PHP ugly code which might be faster
It occurred to me that if there are lots of empty elements at the beginning and end of the array the above method might not be the fastest because it removes them one by one, reindexing the array in each step, etc. So here's a solution that works for any array and does the trimming in just one step. Warning: ugly.
$firstNonEmpty = 0;
$i = 0;
foreach ($array as $val) {
if ($val != '') {
$firstNonEmpty = $i;
break;
}
++$i;
}
$lastNonEmpty = $count = count($array);
end($array);
for ($i = $count; $i > 0; --$i) {
if (current($array) != '') {
$lastNonEmpty = $i;
break;
}
prev($array);
}
$array = array_slice($array, $firstNonEmpty, $lastNonEmpty - $firstNonEmpty);
See it in action.
There ya go :
$Array = array('', Allo, '');
if(isset($Array[0]) && empty($Array[0])){
array_pop($Array);
}
$C = count($Array)-1;
if(isset($Array[$C]) && empty($Array[$C])){
array_shift($Array);
}
It will remove first and last empty only row.
If you want to remove all first and last but only empty you'll need to do this :
$Array = array('', Allo, '', '', 'Toc', '', '', '');
$i=0;
foreach($Array as $Key => $Value){
if(empty($Value)){
unset($Array[$Key]);
} else {
break;
}
$i++;
}
$Array = array_reverse($Array);
$i=0;
foreach($Array as $Key => $Value){
if(empty($Value)){
unset($Array[$Key]);
} else {
break;
}
$i++;
}
$Array = array_reverse($Array);
You can use
array_pop($array); // remove the last element
array_shift($array); // remove the first element
You can do some simple checking before to make sure the first and/or last index is empty
Here's another method:
<?php
$array = array('', '', 'banana', '', 'orange', '', '', '');
while ($array[0] == '')
{
array_shift($array);
}
$count = count($array);
while ($array[$count - 1] == '')
{
array_pop($array);
$count--;
}
print_r($array);
?>
The following snippet will do the job:
function removeStartingEmptyIndexes($array)
{
foreach($array as $i => $item)
{
if(!empty($item)) {
break;
}
else
{
unset($array[$i]);
}
}
return $array;
}
function trimEmptyIndexes($array)
{
return array_reverse(removeStartingEmptyIndexes(array_reverse(removeStartingEmptyIndexes($array))));
}
$array = array("", "", "apple", "orange", "", "", "", "lemon", "", "");
$array = trimEmptyIndexes($array);
Just call "trimEmptyIndexes($array)"
try this
foreach ($original_array as $index => $val) {
if (is_empty($val)) {
unset($original_array [$index]);
} else {
break;
}
}
while(strlen($array[0])==0)
unset(array[0]);
$doLoop=(strlen($array[ count(array)-1 ])==0);
while ($doLoop){
unset($array[ count(array)-1 ]);
$doLoop=(strlen($array[ count(array)-1 ])==0);
}