Remove front part of string using array of removal options - php

Given:
An array of model numbers i.e (30, 50, 55, 85, 120)
a single string that contains model number that is guaranteed to be in the array, immediately followed by a submodel number. Submodel can be a number between 1 and 50.
Examples: 12022, 502, 55123
Wanted:
a single output string containing just the submodel number, i.e 22, 2, 123
aka the front part of string that was in array is removed
Examples: 12022 => 22, 1202 => 2, 502 => 2, 55123 => 123, 5050 => 50
I can think of various ways to do this, but looking for something concise. Bonus if it's also aesthetically beautiful :)

<?php
$arr = array(30, 50, 55, 85, 120); // Array of forbiddens
$str = "12022, 502, 55123"; // Your string
$sep = array_map('trim', explode(",", $str));
foreach($sep as $key => $value)
foreach ($arr as $sec)
if(preg_match("#^$sec#", $value))
$sep[$key] = substr($value, strlen($sec));
print_r($sep);
Output:
Array
(
[0] => 22
[1] => 2
[2] => 123
)

My attempt:
$v = array(120, 50, 55);
print removeModel("502", $v);
function removeModel($str, $v)
{
foreach($v as $value)
if (preg_match("/^$value/",$str))
return preg_replace("/$value/", "", $str);
}

You could use substr($yourString, $x) function to cut first $x characters from $yourString.
My idea:
<?php
$str = "502"; //or "12022" for testing
if(strlen($str)==3)
$newStr=substr($str, (strlen($str)-1)); //502 -> 2
else
$newStr=substr($str, (strlen($str)-2)); //12022 -> 22
echo ltrim($newStr, '0');
?>

just loop the array and replace in the string every array value to empty string

Related

how to obtain the position of an element in an array and in a cycle omit that element?

I´m doing a series of mathematical operations in my web application, and I would like to obtain something like the following:
Given an array of N elements, for example [1,2,3], print on the screen another array with the same number of elements where each position is the multiplication of all elements of the array except the position to be calculated.
The result examples:
[1,2,3] has to print: [6,3,2]
[5,2,3,2,4] has to print: [48,120,80, 120, 60]
You can use array_product() to get the product of all values in your array, and then use array_map() to divide by each value given to "remove" that from the overall product.
$arr = [1, 2, 3];
$product = array_product($arr);
$res = array_map(function ($v) use ($product) {
return $product == 0 ? 0 : $product/$v;
}, $arr);
print_r($res);
Output:
Array ( [0] => 6 [1] => 3 [2] => 2 )
Other cases:
[5, 2, 3, 2, 4] gives [48, 120, 80, 120, 60]
No special array manipulations (slicing/splicing), just super simple math.
Code: (Demo)
$array = [5,2,3,2,4];
foreach ($array as $val) {
$result[] = array_product($array) / $val;
}
var_export($result);
Output:
array (
0 => 48,
1 => 120,
2 => 80,
3 => 120,
4 => 60,
)
You can cache array_product($array) before the loop for greater efficiency. Demo This is effectively the same logic as Nick's answer, I just find it easier to read using language construct versus functional programming.
A normal for loop gives you access to the current index. Within each iteration of the loop you can use array_slice to make a copy and array_splice to remove one element. Then array_reduce with a suitable callback to multiply the remaining values.
function reduce_to_products_without_value_at_index( $initial_array ) {
$num_elements = count( $initial_array );
$product_array = [];
for ( $index = 0; $index < $num_elements; $index++ ) {
$array_copy = array_slice( $initial_array, 0 );
array_splice( $array_copy, $index, 1 );
$product = array_reduce( $array_copy, function( $carry, $item ) {
return $carry * $item;
}, 1 );
$product_array[$index] = $product;
}
print_r( $product_array );
}
reduce_to_products_without_value_at_index( [1,2,3] );
reduce_to_products_without_value_at_index( [5,2,3,2,4] );

Map an array of values to an array of each value's rank in the array

I have a array like this:
$row_arr_1=array(7,9,5,10);
now I want to get the result array like this:
$row_arr_2=array(3,2,4,1);
Explanation:
As 10 is the largest value in row_arr_1, then it will be replaced with value 1.
Similarly, as 9 is the 2nd highest value of row_arr_1, then it will be replaced by 2 and so on.
I tried to sort the values of row_arr_1 but the position is changed.
How
can i get my desired result?
It can be done using rsort() and array_search()
$row_arr_1=array(7,9,5,10);
$row_copy = $row_arr_1;
$row_arr_2 = array();
rsort($row_copy);
foreach($row_arr_1 as $val) {
$row_arr_2[] = array_search($val, $row_copy) + 1;
}
print_r($row_arr_2);
https://eval.in/990078
You can use arsort() to sort the array while preserving keys, and use those keys for your array via array_keys():
$row_arr_1 = array(7,9,5,10);
$row_arr_1_backup = $row_arr_1;
arsort($row_arr_1_backup);
$row_arr_2 = array_keys($row_arr_1_backup);
asort($row_arr_2);
$row_arr_2 = array_keys($row_arr_2);
array_walk($row_arr_2, function(&$item, &$key) {
$item = $item + 1;
});
You have to duplicate the original array, since arsort will sort the actual array it points to, rather than returning a new array.
$row_arr_1_old = array(7, 9, 5, 10);
$row_arr_1 = array(7, 9, 5, 10);
rsort($row_arr_1);
$test = [];
foreach ($row_arr_1_old as $key => $value) {
$test[] = array_search($value, $row_arr_1);
}
print_r($test);
For best efficiency try to reduce total function calls; this especially means minimizing / eliminating iterated function calls.
This is my slightly more efficient version of ahsan's answer.
Code: (Demo)
$copy = $arr = [7, 9, 5, 10];
rsort($arr); // generates: [10, 9, 7, 5]
$flipped = array_flip($arr); // generates: [10 => 0, 9 => 1, 7 => 2, 5 => 3]
foreach($copy as $v) {
$result[] = ++$flipped[$v]; // adds one to each accessed value from $flipped
}
var_export($result);
Output:
array (
0 => 3,
1 => 2,
2 => 4,
3 => 1,
)

How to convert Array to string in PHP without using implode method?

I Have an Array like this,
$arr = array_diff($cart_value_arr,$cart_remove_arr);
I Want to convert it to string without using implode method anyother way is there? And Also i want to remove $cart_remove_arr from $cart_value_arr the array_diff method i used it is correct?
You can use json_encode
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
This will also work on multi dimensional arrays
Will result to:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Doc: http://php.net/manual/en/function.json-encode.php
Another way is the classic foreach plus string concatenation
$string = '';
foreach ($arr as $value) {
$string .= $value . ', ';
}
echo rtrim($string, ', ');
Yet another way is to use serialize() (http://php.net/manual/en/function.serialize.php), as simple as...
$string = serialize($arr);
This can handle most types and unserialize() to rebuild the original value.
$cart_remove_arr = array(0 => 1, 1=> 2, 2 => 3);
$cart_value_arr = array(0 => 5, 1=> 2, 2 => 3, 3 => 4, 4 => 6);
$arr = array_diff($cart_value_arr, $cart_remove_arr);
echo '<pre>';
print_r($arr);
$string = "";
foreach($arr as $value) {
$string .= $value.', ';
}
echo $string;
**Output: Naveen want to remove $cart_remove_arr from $cart_value_arr
Remaining array**
Array
(
[0] => 5
[3] => 4
[4] => 6
)
he want a similar out as implode()
**String** 5, 4, 6,

Displaying number of instances of each array value

$myArray = array(2, 7, 4, 2, 5, 7, 6, 7);
$uniques = array_unique($myArray);
Along with displaying each value in the array only once, how would I ALSO display (in the foreach loop below) the number of times each value is populated in the array. IE next to '7' (the array value), I need to display '3' (the number of times 7 is in the array)
foreach ($uniques as $values) {
echo $values . " " /* need to display number of instances of this value right here */ ;
}
Use the array_count_values function instead.
$myArray = array(2, 7, 4, 2, 5, 7, 6, 7);
$values = array_count_values($myArray);
foreach($values as $value => $count){
echo "$value ($count)<br/>";
}
Have a look at array_count_values.
Quoting from the manual:
Example #1 array_count_values() example
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

How to swap two values in array with indexes?

For example i have an array like this $array = ('a' => 2, 'b' => 1, 'c' => 4); and i need to swap a with c to get this $array = ('c' => 4, 'b' => 1, 'a' => 2);. Wht is the best way for doing this without creating new array? I know that it is possible with XOR, but i also need to save indexes.
array_splice would be perfect, but unfortunately it doesn't preserve the keys in the inserted arrays. So you'll have to resort to a little more manual slicing and dicing:
function swapOffsets(array $array, $offset1, $offset2) {
list($offset1, $offset2) = array(min($offset1, $offset2), max($offset1, $offset2));
return array_merge(
array_slice($array, 0, $offset1, true),
array_slice($array, $offset2, 1, true),
array_slice($array, $offset1 + 1, $offset2 - $offset1 - 1, true),
array_slice($array, $offset1, 1, true),
array_slice($array, $offset2 + 1, null, true)
);
}
If you want to purely swap the first and the last positions, here's one way to do it:
$first = array(key($array) => current($array)); // Get the first key/value pair
array_shift($array); // Remove it from your array
end($array);
$last = array(key($array) => current($array)); // Get the last key/value pair
array_pop($array); // Remove it from the array
$array = array_merge($last, $array, $first); // Put it back together
Gives you:
Array
(
[c] => 4
[b] => 1
[a] => 2
)
Working example: http://3v4l.org/r87qD
Update: And just for fun, you can squeeze that down quite a bit:
$first = array(key($array) => current($array));
$last = array_flip(array(end($array) => key($array)));
$array = array_merge($last, array_slice($array,1,count($array) - 2), $first);
Working example: http://3v4l.org/v6R7T
Update 2:
Oh heck yeah, we can totally do this in one line of code now:
$array = array_merge(array_flip(array(end($array) => key($array))), array_slice($array,1,count($array) - 2), array_flip(array(reset($array) => key($array))));
Working example: http://3v4l.org/QJB5T
That was fun, thanks for the challenge. =)

Categories