I have 2 arrays merge to one array, Now i want to check if value 1 in array $b
then add special content value to $b
in foreach.
But in below example added the content to $s
and $b
$s = array(1,2,3,4,5);
$b = array(1,2,3,4);
$one = array_merge($s,$b);
$arr = array_chunk($one, 1);
foreach($arr as $k=>$v){
if(in_array($arr[$k][0],$b)){
echo "c";
}
echo $arr[$k][0]."<br>";
}
Output
c1
c2
c3
c4
5
c1
c2
c3
c4
And i want that output
1
2
3
4
5
c1
c2
c3
c4
It's Simple. You just have to check with the if condition. If the loop has been repeated more than the length of the array $s, then do echo "c";
$s = array(1,2,3,4,5);
$b = array(1,2,3,4);
$one = array_merge($s,$b);
$arr = array_chunk($one, 1);
$s_length = count($s);
$i = 1;
foreach($arr as $k=>$v){
// Check if the loop has been repeated more than the length of the array $s
if($i > $s_length){
echo "c";
}
echo $arr[$k][0]."<br>";
$i++;
}
I don't know exactly if that is what you want but:
$s = array(1,2,3,4,5);
$b = array(1,2,3,4);
$arr = array_diff($s, $b);
// Search differences between diff() and $s
$cs= "";
$cb= "";
// If array have semantical keys we'll do an array_values()
foreach ( array_values($arr) as $k => $v ){
// If $cs is actually set as 'c'
if ( "c"!=$cs ){
// If a value in the diff() array are not in s => $cs = 'c'
$cs= ( !in_array( $v, $s ,true ))? "c": "";
}
// If $cb is actually set as 'c'
if ( "c"!=$cb ){
$cb= ( !in_array( $v, $b ,true ))? "c" : "";
}
}
// Print each array values with associated $c
foreach ( $s as $k => $v ){
echo "<br>$cs$v" ;
}
foreach ( $b as $k => $v ){
echo "<br>$cb$v" ;
}
Output:
1
2
3
4
5
c1
c2
c3
c4