Compare two strings and remove or replace same characters in php - php

I want to compare two strings (variable1 and variable2) and i want to remove the matching characters from both strings(Only once).
For example: Variable1 : Apple, Variable2 : Ball
I tried using
array_diff(str_split('ball'), str_split('apple'))
but i got only
b (it removed all matching characters.)
Expected Output is
bl (letters A,L(only once) removed from the second strings.)
ppe (letters A,L(only once) removed from the first strings.)
How to remove the characters only once ?

You need to do workaround for this using foreach() like below:-
$array1 = str_split(strtolower($variable1));
$array2 = str_split(strtolower($variable2));
if(count($array1) >= count($array2)){
foreach($array1 as $key=>$arr){
foreach($array2 as $k=>$arr2){
if($arr == $arr2){
unset($array1[$key]);
unset($array2[$k]);
break;
}
}
}
}
if(count($array2) >= count($array1)){
foreach($array2 as $key=>$arr){
foreach($array1 as $k=>$arr1){
if($arr == $arr1){
unset($array2[$key]);
unset($array1[$k]);
break;
}
}
}
}
print_r($array1);
print_r($array2);
Output:- https://3v4l.org/dp0ui

You can handle this through for-each
$a = 'ball';
$b = 'apple';
$arr1 = str_split($a);
$arr2 = str_split($b);
$firstArr = ( count($arr1) > count($arr2) ) ? $arr2 : $arr1;
$secondArr = ( count($arr1) < count($arr2) ) ? $arr2 : $arr1;
$objSecondArray = [];
$res = [];
foreach ($secondArr as $value) {
$objSecondArray[$value] = 1;
}
foreach( $firstArr as $val ){
if(array_key_exists($val, $objSecondArray) && $objSecondArray[$val] == 1) {
$objSecondArray[$val] = null;
continue;
}
$res[] = $val;
}
print_r($res);

Related

How to add string into array in PHP?

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo

How to replace array value with another array value using php?

I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}

Make two arrays from and array in php [duplicate]

I have this array:
$array = array(a, b, c, d, e, f, g);
I want to split it in two arrays depending if the index is even or odd, like this:
$odd = array(a, c, e, g);
$even = array(b, d, f);
Thanks in advance!
One solution, using anonymous functions and array_walk:
$odd = array();
$even = array();
$both = array(&$even, &$odd);
array_walk($array, function($v, $k) use ($both) { $both[$k % 2][] = $v; });
This separates the items in just one pass over the array, but it's a bit on the "cleverish" side. It's not really any better than the classic, more verbose
$odd = array();
$even = array();
foreach ($array as $k => $v) {
if ($k % 2 == 0) {
$even[] = $v;
}
else {
$odd[] = $v;
}
}
Use array_filter (PHP >= 5.6):
$odd = array_filter($array, function ($input) {return $input & 1;}, ARRAY_FILTER_USE_KEY);
$even = array_filter($array, function ($input) {return !($input & 1);}, ARRAY_FILTER_USE_KEY);
I am not sure if this is the most elegant way, but it should work a charm:
$odd=array();
$even=array();
$count=1;
foreach($array as $val)
{
if($count%2==1)
{
$odd[]=$val;
}
else
{
$even[]=$val;
}
$count++;
}
As an almost-one-liner, I think this will be my favourite:
$even = $odd = array();
foreach( $array as $k => $v ) $k % 2 ? $odd[] = $v : $even[] = $v;
Or for a tiny little more? speed:
$even = $odd = array();
foreach( $array as $k => $v ) ( $k & 1 ) === 0 ? $even[] = $v : $odd[] = $v;
A bit more verbose variant:
$both = array( array(), array() );
// or, if $array has at least two elements:
$both = array();
foreach( $array as $k => $v ) $both[ $k % 2 ][] = $v;
list( $even, $odd ) = $both;
With array_chunk:
$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk ){
list( $even[], $odd[] ) = isset( $chunk[1]) ? $chunk : $chunk + array( null, null );
// or, to force even and odd arrays to have the same count:
list( $even[], $odd[] ) = $chunk + array( null, null );
}
If $array is guaranteed to have even number of elements:
$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk )
list( $even[], $odd[] ) = $chunk;
PHP 5.5.0+ with array_column:
$chunks = array_chunk( $array, 2 );
$even = array_column( $chunks, 0 );
$odd = array_column( $chunks, 1 );
Something similar for older PHP versions.
The keys will be 0,2,4,… and 1,3,5,…. If you don't like this, apply an array_values too:
$even = array_intersect_key( $array, array_flip( range( 0, count( $array ), 2 )));
$odd = array_intersect_key( $array, array_flip( range( 1, count( $array ), 2 )));
or
$even = array_intersect_key( $array, array_fill_keys( range( 0, count( $array ), 2 ), null ));
$odd = array_intersect_key( $array, array_fill_keys( range( 1, count( $array ), 2 ), null ));
One more functional solution with array_chunk and array_map. The last line removes empty item from the 2nd array, when size of a source array is odd
list($odd, $even) = array_map(null, ...array_chunk($ar,2));
if(count($ar) % 2) array_pop($even);
Just loop though them and check if the key is even or odd:
$odd = array();
$even = array();
foreach( $array as $key => $value ) {
if( 0 === $key%2) { //Even
$even[] = $value;
}
else {
$odd[] = $value;
}
}
One
$odd = $even = array();
for ($i = 0, $l = count($array ); $i < $l;) { // Notice how we increment $i each time we use it below, by two in total
$even[] = $array[$i++];
if($i < $l)
{
$odd[] = $array[$i++];
}
}
Two
$odd = $even = array();
foreach (array_chunk($array , 2) as $chunk) {
$even[] = $chunk[0];
if(!empty( $chunk[1]))
{
$odd[] = $chunk[1];
}
}
Based on #Jon's second variant, I made this following for use with PHP Smarty v3 template engine. This is for displaying news/blog with both one or two columns template model.
After the MySql query I'll do the following code :
if(sizeof($results) > 0) {
$data = array();
foreach($results as $k => $res) {
if($k % 2 == 0) {
$res["class"] = "even";
$data["all"][] = $data["even"][] = $res;
}
else {
$res["class"] = "odd";
$data["all"][] = $data["odd"][] = $res;
}
}
}
I obtain an array of 3 sub-arrays (including odd/even class) with Smarty syntax of use :
all items {foreach $data.all as $article}...{/foreach}
odd items only {foreach $data.odd as $article}...{/foreach}
even items only {foreach $data.even as $article}...{/foreach}
Hope it helps some people...
$odd = [];
$even = [];
while (count($arr)) {
$odd[] = array_shift($arr);
$even[] = array_shift($arr);
}
<?php
$array1 = array(0,1,2,3,4,5,6,7,8,9);
$oddarray = array();
$evenarray = array();
$count = 1;
echo "Original: ";
foreach ($array1 as $value)
{
echo "$value";
}
echo "<br> Even: ";
foreach ($array1 as $print)
{
if ($count%2==1)
{
$evenarray = $print;
echo "$print";
}
$count++;
}
echo "<br> Odd: ";
foreach ($array1 as $print2) {
if ($count%2!=1)
{
$oddarray[] = $print2;
echo "$print2";
}
$count++;
}
?>
Output:
Original: 0123456789
Even: 02468
Odd: 13579

Merge every other array php

array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?
You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.
Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}
This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO
if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help
Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];

Categories