Find position and get before and after? - php

$x = "P-29042011386693";
$array = "P-28042011135870,P-28042011132333,P-28042011384621,P-29042011386693,P-29042011384190,P-29042011388434,P-29042011382454,P-29042011385512,P-29042011383902";
$array = explode(",", $array);
$count = count($array);
$search = array_search($x, $array);
if (($search > 0) && ($search < $count)){
$before = $array[$search-1];
$after = $array[$search+1];
}elseif ($search == 0){
$before = NULL;
$after = $array[1];
}elseif ($search == $count){
$before = $array[$count-1];
$after = NULL;
}
What is the best way to detect the value before $x and the value after $x, and display $before or $after as blank if there is no result before/after $x?
So if $x was P-29042011383902 - $after would be blank and $before would be P-29042011385512
If $x was P-28042011135870 $before would be blank and $after would be P-28042011132333
Is my code above right?

$search = array_search($x, $array);
if (false === $search) {
throw new Exception('Not found', 404);
}
$before = isset($array[$search - 1]) ? $array[$search - 1] : null;
$after = isset($array[$search + 1]) ? $array[$search + 1] : null;

Something like this?
$eachone = explode (" ,", $row);
6 is $eachone[6]
5 is $eachone[6-1]
If i understood the question, that's it.
With new information:
The example at php.net is this:
$str = "Hello Friend";
$arr1 = str_split($str); and you get an array like this
Array
(
[0] => H[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)

Related

How to split array in php?

I am little bit confused to get first and last value from array. And I tried to use explode()function but my logic is not working properly and very stupid logic.
My array
Array
(
[0] => 500 - 1112
[1] => 1113 - 2224
[2] => 2225 - 4446
[3] => 4446
)
I tried this way
$range = explode(',', $price_range);
$count = count($range);
if (1 == $count) {
$price_1 = $range[0];
$ranges['range1'] = explode(' - ', $price_1);
} else if (2 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
} else if (3 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$price_3 = $range[2];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
$ranges['range3'] = explode(' - ', $price_3);
} else if (4 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$price_3 = $range[2];
$price_4 = $range[3];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
$ranges['range3'] = explode(' - ', $price_3);
$ranges['range4'] = explode(' - ', $price_4);
}
$array = call_user_func_array('array_merge', $ranges);
sort($array);
$min = reset($array);
$max = end($array);
As per my array I want if in array getting single value in array for example
Array
(
[0] => 500 - 1112
[1] => 1113 - 2224
[2] => 2225 - 4446
[3] => 4446
)
So I want to convert this array as shown below,
Array
(
[0] => array(
[0] => 500
[1] => 1112
[2] => 1113
[3] => 2224
[4] => 2225
[5] => 4446
)
[1] => 4446
)
And get min and max from Array ( [0] => array( from this array. Is their any simple way to do.
Thanks in advance
If I correctly understand your example, you provided it with the parameter $count to 2.
So, this could be my version of your request:
The data
<?php
$data[] = '500 - 1112';
$data[] = '1113 - 2224';
$data[] = '4446';
The function
<?php
function explodeRanges(array $data, $counter, $explode = '-') {
$return = [];
// We take the correct number of rows
foreach( array_slice($data, 0, $counter) as $value ) {
$return = array_merge(
$return,
array_map('trim', explode($explode, $value))
);
// trim() function mapped on each elements to clean the data (remove spaces)
// explode all values by the separator
}
return $return;
}
The output
<?php
for( $i = 1 ; $i <= 4 ; $i++ ) {
$range = explodeRanges($data, $i);
echo 'For ', $i, ' => [', implode(', ', $range), ']; MIN = ', min($range), '; MAX = ', max($range);
echo '<hr />';
}
... and the result :)
For 1 => [500, 1112]; MIN = 500; MAX = 1112
For 2 => [500, 1112, 1113, 2224]; MIN = 500; MAX = 2224
For 3 => [500, 1112, 1113, 2224, 4446]; MIN = 500; MAX = 4446
For 4 => [500, 1112, 1113, 2224, 4446]; MIN = 500; MAX = 4446
If you need to repeat your code several times, it's because you can improve it. Here it's quick with a simple function.

i need a PHP code to find longest contiguous sequence of characters in the string

I need a PHP code to find longest contiguous sequence of characters in the string. So if b is coming together for maximum number of times your program should echo b and count
Example string:
aaabababbbbbaaaaabbbbbbbbaa
Output must be:
b 8
Using
- preg_match_all to get sequences of repeating characters,
- array_map along with strlen to get the string length of each sequence
- max to get the biggest value in the array.
Consider the following example:
$string = "aaabababbbbbaaaaabbbbbbbbaa";
preg_match_all('#(\w)\1+#',$string,$matches);
print_r($matches);
Will output
Array
(
[0] => Array
(
[0] => aaa
[1] => bbbbb
[2] => aaaaa
[3] => bbbbbbbb
[4] => aa
)
[1] => Array
(
[0] => a
[1] => b
[2] => a
[3] => b
[4] => a
)
)
Next we get the sizes for each string of repeating characters
$sizes = array_map('strlen', $matches[0]);
print_r($sizes);
Will output
Array
(
[0] => 3
[1] => 5
[2] => 5
[3] => 8
[4] => 2
)
Now let's get the biggest value of the $sizes array
print max($sizes);
Will give us
8
We need the key for the max value to pick up the letter
$maxKey = array_keys($sizes, max($sizes));
print $matches[1][$maxKey[0]];
Will output
b
Since you're looking for continuous sequences:
$string = 'aaabababbbbbaaaaabbbbbbbbaa';
$count = strlen($string);
if ($count > 0)
{
$mostFrequentChar = $curChar = $string[0];
$maxFreq = $curFreq = 1;
for ($i = 1; $i < $count; $i++)
{
if ($string[$i] == $curChar)
{
$curFreq++;
if ($curFreq > $maxFreq)
{
$mostFrequentChar = $curChar;
$maxFreq = $curFreq;
}
}
else
{
$curChar = $string[$i];
$curFreq = 1;
}
}
}
echo $mostFrequentChar . ' ' . $maxFreq;
$string = 'aaabababbbbbaaaaabbbbbbbbaa';
$occurrence = [];
$count = strlen($string);
for ($x = 0; $x < $count; $x++) {
if(isset($ocurrence[$string[$x]])) {
$ocurrence[$string[$x]]++;
} else {
$ocurrence[$string[$x]] = 0;
}
}
var_dump($occurrence);
This should do the trick.
<?php
$x = "aaaaaaabbbbbbbaaaacccccccaaaaaaaaaaaaaaaaabbbbbbaaaaadddddddddddddddddddddddddddddddddd";
$count = strlen($x);
$y =array();
$n =0;
$d =1;
$first = $x{1};
for($j = $d;$j < $count;$j++)
{
if($x{$j} == $first )
{
$y[$j] = $x{$j};
$first = $x{$j};
}
elseif($x{$j} != $first )
{
$y[$j] = ",".$x{$j};
$first = $x{$j};
}
}
$xy = implode("",$y);
$xy1 = explode(",",$xy);
$c_count = count($xy1);
$dg = 1;
for($g = 0;$g < $c_count;$g++)
{
$cnt = strlen($xy1[$g]);
$cntm = $xy1[$g];
$replace = $cntm{1};
if($cnt > $dg)
{
$ab = str_replace($cntm,$replace,$cntm);
$dg = $cnt.".".$ab ;
}
}
echo $dg;
?>

How to split slash / separated string in two variable in php

Assume that applicant id was passed from the other form.I have array variable coming from my database, here is the code :
$array_id_applicants = explode(";",stripslashes($applicant_id1));
$applicants_num = count($array_id_applicants);
$arr_app_num = array();
for($x=0;$x<=$applicants_num;$x++)
{
if($array_id_applicants[$x]){
$applicant_id = str_replace("'","",$array_id_applicants[$x]);
$applicants = getdata("select cellphone from personal where applicant_id='".$applicant_id."'");
$replace_array = array("-","(",")","+","_");
array_push($arr_app_num,str_replace($replace_array,"",$applicants[1][cellphone]));
}
}
$applicant_number = implode(";",$arr_app_num);
echo $applicant_number; exit;
Assume that this is the value of array :
$applicant_number = '639152478931 / 631687515455','631235497891'
I want the output to be like this :
$applicant_number = '639152478931','631687515455','631235497891'
See if this is what you are trying to do.:
<?php
$applicant_number[] = '639152478931 / 631687515455';
$applicant_number[] = '631235497891';
$applicant_number[] = '0294765388389 / 52525252525';
$applicant_number[] = '0012324252728';
$new = array();
foreach($applicant_number as $number) {
if(strpos($number,'/') !== false) {
$val = explode("/",str_replace(" ","",$number));
$new = array_merge($new,$val);
}
else
$new[] = $number;
}
print_r($new);
?>
Gives you:
Array
(
[0] => 639152478931
[1] => 631687515455
[2] => 631235497891
[3] => 0294765388389
[4] => 52525252525
[5] => 0012324252728
)
<?php
$applicant_number[] = '639152478931';
$applicant_number[] = '631235497891';
$applicant_number[] = '1111111110294765388389';
$applicant_number[] = '0012324252728';
$new = array();
foreach($applicant_number as $number) {
$count = strlen($number) - 10;
$b = substr($number,$count);
$new[] = "+63".$b;
}
print_r($new);
?>
Gives you :
Array ( [0] => +639152478931 [1] => +631235497891 [2] => +634765388389 [3] => +632324252728 )

How can I pull out Variables from XML "Like" string of text and numbers using PHP?

Here's what I have to work with:
$sample = '<VAR1>TEXT</VAR1><BR><NUM1>123456789</NUM1><BR><NUM2>9</NUM2><BR><NUM3>99</NUM3>';
Here's what I would like to end up with:
$VAR1 = 'TEXT';
$NUM1 = 123456789;
$NUM2 = 9;
$NUM3 = 99;
Thank you in advance, I'm sure the solution is simple, however everything I've tried hasn't worked thus far.
This is really Really REALLY SLOPPY (I'll say that right up front) but it does work...
<?PHP
$a = '<VAR1>TEXT</VAR1><BR><NUM1>123456789</NUM1><BR><NUM2>9</NUM2><BR><NUM3>99</NUM3>';
preg_match_all("(\<.+\>(.+)\<\/.+\>)U",$a, $r);
// 4 TESTING //
echo '$r:<pre>';
print_r($r);
echo '</pre><hr>';
/*
$r Array
(
[0] => Array
(
[0] => <VAR1>TEXT</VAR1>
[1] => <BR><NUM1>123456789</NUM1>
[2] => <BR><NUM2>9</NUM2>
[3] => <BR><NUM3>99</NUM3>
)
[1] => Array
(
[0] => TEXT
[1] => <NUM1>123456789
[2] => <NUM2>9
[3] => <NUM3>99
)
)
*/
$demo = array();
$demo = array_combine ( array('VAR1'), sscanf($a, '<VAR1>%[^<]</VAR1>') );
foreach ($r[1] as $key => $value) {
if (strpos($value, '<NUM1>') !== false) {
$clean = str_replace("<NUM1>", "", $value);
$demo['NUM1'] = trim($clean);
}elseif (strpos($value, '<NUM2>') !== false) {
$clean = str_replace("<NUM2>", "", $value);
$demo['NUM2'] = trim($clean);
}elseif (strpos($value, '<NUM3>') !== false) {
$clean = str_replace("<NUM3>", "", $value);
$demo['NUM3'] = trim($clean);
}else{
}//end if
}//end foreach
// 4 TESTING //
echo 'DEMO:<pre>';
print_r($demo);
echo '</pre><hr>';
/*
$demo Array
(
[VAR1] => TEXT
[NUM1] => 123456789
[NUM2] => 9
[NUM3] => 99
)*/
?>

how to merge some elements array in php? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
example:
Array (
[0] => 35
[1] => -
[2] => 59
[3] => *
[4] => 2
[5] => /
[6] => 27
[7] => *
[8] => 2 )
then calculated:
59*2=118
and the new array is:
Array (
[0] => 35
[1] => -
[2] => 118
[3] => /
[4] => 27
[5] => *
[6] => 2 )
this is my original source :
input ($_POST['numbers']) is a string, LIKE:
65*6/6+5-5
class calculator {
//property
private $str='';
private $len=0;
private $ar_str=array();
private $ar_design=array();
private $ar_sum=array();
private $ar_min=array();
private $ar_mult=array();
private $ar_divi=array();
//Method
public function __construct($str1=''){
$this->str=$str1;
$this->len=strlen($this->str);
$this->ar_str=str_split($this->str);
if($this->ar_str[0] == '+' ||
$this->ar_str[0] == '-' ||
$this->ar_str[0] == '*' ||
$this->ar_str[0] == '/' ||
$this->ar_str[$this->len-1] == '+' ||
$this->ar_str[$this->len-1] == '-' ||
$this->ar_str[$this->len-1] == '*' ||
$this->ar_str[$this->len-1] == '/'
){
exit("Syntax error!");
}else if(!filter_var($this->ar_str[0], FILTER_VALIDATE_INT)){
exit("just use numbers and 4 operators!");
}
$this->ar_design[0]=$this->ar_str[0];
//start for
$j=1;
for($i=1;$i<$this->len;$i++){
if($this->ar_str[$i] == '+' || $this->ar_str[$i] == '-' || $this->ar_str[$i] == '*' || $this->ar_str[$i] == '/'){
if($this->ar_str[$i-1] == '+' || $this->ar_str[$i-1] == '-' || $this->ar_str[$i-1] == '*' || $this->ar_str[$i-1] == '/'){
exit("Syntax error!");
}else{
$this->ar_design[$j]=$this->ar_str[$i];
$j++;
}
}else if(filter_var($this->ar_str[$i], FILTER_VALIDATE_INT)){
if($this->ar_str[$i-1] == '+' || $this->ar_str[$i-1] == '-' || $this->ar_str[$i-1] == '*' || $this->ar_str[$i-1] == '/'){
$this->ar_design[$j]=$this->ar_str[$i];
}else{
$j--;
$this->ar_design[$j]=$this->ar_design[$j].$this->ar_str[$i];
}
$j++;
}else{
exit("just use numbers and 4 operators!");
}
}//end of for
print_r($this->ar_design);//array this array should be calculate!!!!!
}//end construct
}
if(isset($_POST['numbers'])){
$num_str=trim($_POST['numbers']);
if($num_str!=''){
$num_str = str_replace('`','+',$num_str);
new calculator($num_str);
}
}
i could find the answer:
$this->len_d=count($this->ar_design);
$this->ar_cal[0]=$this->ar_design[0];
$k=1;
for($i=1;$i<$this->len_d;$i++){
if($this->ar_design[$i] == '*'){
$k--;
$this->ar_cal[$k]=$this->ar_design[$i-1]*$this->ar_design[$i+1];
$i++;
}else{
$this->ar_cal[$k]=$this->ar_design[$i];
}
$k++;
}
print_r($this->ar_cal);
You could do it with a loop and then executing it.
$array=Array (35,'-',59,'*',2,'/',27,'*',2);
foreach ($array as $value){
$stringify.=$value;
}
echo 'Calculation looks like this: '.$stringify.'<br/>';
function calculate( $math ){
$calc = create_function("", "return (" .$math. ");" );
return $calc();
}
echo calculate($stringify);
could be imroved, for example by validating the input...
Working example: http://allanthya.net/arrcalc2.php
<?php
$array = array( 35, '-', 59, '*', 2, '/', 27, '*', 2 );
print_r($array);
echo "<p>";
while ( true ) {
$div = array_keys($array, '/');
$mult = array_keys($array, '*');
$add = array_keys($array, '+');
$sub = array_keys($array, '-');
if ( count($div) >= 1 ) {
$index = $div[0];
$op1 = $array[$index-1];
$op2 = $array[$index+1];
$array[$index] = $op1 / $op2;
unset($array[$index-1]);
unset($array[$index+1]);
$array = array_values($array);
continue;
} else if ( count($mult) >= 1 ) {
$index = $mult[0];
$op1 = $array[$index-1];
$op2 = $array[$index+1];
$array[$index] = $op1 * $op2;
unset($array[$index-1]);
unset($array[$index+1]);
$array = array_values($array);
continue;
} else if ( count($add) >= 1 ) {
$index = $add[0];
$op1 = $array[$index-1];
$op2 = $array[$index+1];
$array[$index] = $op1 + $op2;
unset($array[$index-1]);
unset($array[$index+1]);
$array = array_values($array);
continue;
} else if ( count($sub) >= 1 ) {
$index = $sub[0];
$op1 = $array[$index-1];
$op2 = $array[$index+1];
$array[$index] = $op1 - $op2;
unset($array[$index-1]);
unset($array[$index+1]);
$array = array_values($array);
continue;
}
else {
break;
}
}
print_r($array);
echo "<p>";
?>
Heres the output of a print_r() after each iteration of the while loop so you can see it running through the divisions, multiplications, additions and subtractions one by one and thn modifying the array as it goes:
Array ( [0] => 35 [1] => - [2] => 59 [3] => * [4] => 2 [5] => / [6] => 27 [7] => * [8] => 2 )
Array ( [0] => 35 [1] => - [2] => 59 [3] => * [4] => 0.0740740740741 [5] => * [6] => 2 )
Array ( [0] => 35 [1] => - [2] => 4.37037037037 [3] => * [4] => 2 )
Array ( [0] => 35 [1] => - [2] => 8.74074074074 )
Array ( [0] => 26.2592592593 )
Why not calculate as you go splitting the input into an array, and then just output the result?
Just as an example:
$input = "35-59*2/27*2";
if (preg_match('/[^-+*\/\\d]/', $input)) // simple checking
{
echo "just use numbers and 4 operators!";
}
else
{
$substraction = explode('-', $input);
foreach ($substraction as $pos_s => $sub)
{
$addition = explode('+', $sub);
foreach ($addition as $pos_a => $add)
{
$multiplication = explode('*', $add);
foreach ($multiplication as $pos_m => $mult)
{
$division = explode('/', $mult);
$d = $division[0];
for ($i=1; $i < count($division);$i++)
$d = $d / $division[$i];
$multiplication[$pos_m] = $d;
}
$m = $multiplication[0];
for ($i=1; $i < count($multiplication);$i++)
$m = $m * $multiplication[$i];
$addition[$pos_a] = $m;
}
$a = $addition[0];
for ($i=1; $i < count($addition);$i++)
$a = $a + $addition[$i];
$substraction[$pos_s] = $a;
}
$result = $substraction[0];
for ($i=1; $i < count($substraction);$i++)
$result = $result - $substraction[$i];
echo $input . " = " . $result;
}
prints
35-59*2/27*2 = 26.259259259259

Categories