how Delete a value in Array php - php

Please help
when i want yo remove an element from array buu after when i print array it shows error
4
6
2
NOTICE Undefined offset: 3 on line number 16
<?php
$value = 22;
$numbers = array(4, 6, 2, 22, 11);
$arrlength = count($numbers);
for($y = 0; $y < $arrlength ; $y++) {
if ( $numbers[$y] == $value) {
unset($numbers[$y]);
}
}
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>

You should use "array_values()" to re-index the array. You can find the explication here : http://php.net/manual/en/language.types.array.php#language.types.array.useful-funcs

Use array_values().
<?php
$value = 22;
$numbers = array(4, 6, 2, 22, 11);
$arrlength = count($numbers);
for($y = 0; $y < $arrlength ; $y++) {
if ( $numbers[$y] == $value) {
unset($numbers[$y]);
}
}
$numbers = array_values($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Check Online Demo : Click Here
OR
<?php
$value = 22;
$numbers = array(4, 6, 2, 22, 11);
$arrlength = count($numbers);
for($y = 0; $y < $arrlength ; $y++) {
if ( $numbers[$y] == $value) {
unset($numbers[$y]);
}
}
//$numbers = array_values($numbers);
//$arrlength = count($numbers);
foreach($numbers as $key=>$num) {
echo $num;
echo "<br>";
}
?>

you are trying to print element of not existing key
try this:
<?php
$value = 22;
$numbers = array(4, 6, 2, 22, 11);
$arrlength = count($numbers);
for($y = 0; $y < $arrlength ; $y++) {
if ( $numbers[$y] == $value) {
unset($numbers[$y]);
}
}
foreach($numbers as $k => $number)
echo "key: ". $k . " value: ". $number . "<br />";

Related

How can i add + sign

<?php
$numbers = array("12", "-32", "52", "-65", "98");
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
How can i add + sign where is not - minus.
Result:
+12,
-32,
+52,
-65,
+98
you can add condition like this:
echo (int)$numbers[$x] > 0 ? '+'.$numbers[$x] : $numbers[$x];
so it will be
$numbers = array("12", "-32", "52", "-65", "98");
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo ((int)$numbers[$x] > 0) ? '+'.$numbers[$x] : $numbers[$x];
echo "<br>";
}
For a very straight forwards echo modification, replace
echo $numbers[$x];
with
echo ( $numbers[$x] > 0 ) ? '+'.$numbers[$x] : $numbers[$x];

Calculate sum of Primary and Secondary Diagonal in square matrix

I am currently calculating diagonal for n x n square matrix. I can able to calculate Primary diagonal with below code.
function calculateDiagonal($array) {
$length = count($array);
$primary = 0;
$secondary = 0;
for ($i = 0; $i < $length; $i++):
for ($j = 0; $j < $length; $j++):
if ($i == $j):
$primary += $array[$i][$j];
endif;
endfor;
endfor;
$totalSum = $primary + $secondary;
return $totalSum;
}
Can anyone help me to calculate sum of secondary diagonal.
check this as a reference.
Please try with this. You can do sum of diagonal with minimum iteration.
$a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
$n = 4;//nxn matrix
$d = $s = 0; //initialize both diagonal sum to 0
for ($i = 0; $i < $n; $i++) {
$d += $a[$i][$i];
$s += $a[$i][$n - $i - 1];
}
var_dump($d);//primary diagonal total
var_dump($s);//secondary diagonal total
Try this
function calculate2Diagonal($array) {
$length = count($array)-1;
$primary = 0;
$secondary = 0;
echo $length;
for ($i = $length; $i >= 0; $i--):
for ($j = $length; $j >=0; $j--):
if ($i == $j):
$primary += $array[$i][$j];
endif;
endfor;
endfor;
$totalSum = $primary + $secondary;
return $totalSum;
}
Only a for inverse ;)
Just using the function array_reduce:
function diagonalSum($arr) {
$i = 0;
$n = count($arr);
return array_reduce($arr,
function ($c, $str) use (&$i, $n ) {
$i++;
return $c + $str[$i-1] + $str[$n-$i];
}, 0);
}
demo

How to count how many duplicates an array has in Php

I'm new to Php and today I came across the rand()-function. I'd like to fill an array with numbers created with this function and then count the number of its duplicates. I already tried it a first time, but somehow I seem to be on the woodway.
<?php
$numbers = array();
for ($i=0; $i < 100; $i++) {
$numbers[$i] = rand(0, 100);
}
//$numbers = array(12,12,12,12);
echo "random numbers generated.<br>";
$arrLength = count($numbers);
$arrWithDoubles = array();
for ($i=0; $i < $arrLength; $i++) {
//echo "start looping for i: ".$i."! numbers['i'] has the content".$numbers[$i].".<br>";
for ($x=$i; $x < $arrLength; $x++) {
//echo "looped for x: ".$x."! numbers['x'] has the content".$numbers[$x].".<br>";
if($numbers[$i] == $numbers[$x]) {
if($i != $x) {
//echo "pushed to 'arrWithDoubles'.<br>";
array_push($arrWithDoubles, $numbers[$x]);
}
}
}
}
echo "numbers of doubles: ".count($arrWithDoubles)."<br>";
echo "list of numbers which were double:<br>";
for ($i=0; $i < count($arrWithDoubles); $i++) {
echo $arrWithDoubles[$i];
echo "<br>";
}
?>
The array_unique() function removes duplicates from an array, then just add a bit of math.
<?php
$numberOfDuplicates = count($orginalArray) - (count($orginalArray) - count(array_unique($originalArray)));
?>
$origin = array(2,4,5,4,6,2);
$count_origin = count($origin);
$unique = array_unique($origin);
$count_unique = count($unique);
$duplicates = $count_origin - $count_unique;
echo $duplicates;
$count = array();
foreach ($srcRandom as $sr) {
if (!array_key_exists ($sr, $count) ) {
$count[$sr] = 1;
continue;
}
$count[$sr]++;
}
var_dump ($count);
Thanks for all your input. With that I came to the following solution which fits my demand the best:
<?php
function countValueInArray($value, $array) {
$count = 0;
for ($i=0; $i < count($array); $i++) {
if($value == $array[$i]) {
$count++;
}
}
return $count;
}
$numbers = array();
for ($i=0; $i < 100; $i++) {
$numbers[$i] = rand(0, 100);
}
$duplicates = array();
for ($x=0; $x < count($numbers); $x++) {
$number = countValueInArray($numbers[$x], $numbers);
if ($number > 1) {
array_push($duplicates, $numbers[$x]);
}
}
$duplicatesList = array_values(array_unique($duplicates));
echo "number of duplicates: ".count($duplicatesList);
echo "<br>these are: <br>";
print_r($duplicatesList);
?>
Thanks a lot for your help!

Get all unique combinations from array for a given number of elements

I wanted to have a way to get all combinations for all given numbers with given array length.
In my project the array size usually is 7. So I write a test code like this to see if I can get all needed combinations. The important part is every result array must be unique and maximum array size must be 7.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7];
$arraysize = 7;
$subset = [];
$count = count($numbers);
for ($i = 0; $i < $count; $i++) {
$subset[] = $numbers[$i];
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
$subset[] = $numbers[$i] . $numbers[$j];
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k];
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l];
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m];
}
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
for ($n=$m; $n < $count; $n++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m] . $numbers[$n];
}
}
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
for ($n=$m; $n < $count; $n++) {
for ($o=$n; $o < $count; $o++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m] . $numbers[$n] . $numbers[$o];
}
}
}
}
}
}
}
echo "<pre>";
print_r($subset);
echo "</pre>";
?>
When I run this code I get the combinations like I wanted (I make the combinations as string to see the results clearly but normally every result item in $subset array must be array)
With this code I can get all unique combinations.
But as you can see this code is ugly. I tried to make this a recursive function but I failed. Could anyone point me to right direction to get the exact same results like this? (every item in $subset array normally must be an array that contains digits)
You can simplify this logic (and make the code less ugly) without needing to go recursive by using:
for ($i = 0; $i < $count; $i++) {
$subset[] = $numbers[$i];
for ($j=$i; $j < $count; $j++) {
$subset[] = $numbers[$i] . $numbers[$j];
for ($k=$j; $k < $count; $k++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k];
for ($l=$k; $l < $count; $l++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l];
}
}
}
}
the following will work in all cases even if you have duplicate numbers in your array
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
sort($array); //in case it 's not sorted
$array = array_slice($array,-7);
$num = count($array );
$total = pow(2, $num);
$result= array();
$element='';
for ($i = 0; $i < $total; $i++)
{
for ($j = 0; $j < $num; $j++)
{
if (pow(2, $j) & $i)
{
$element=$element.$array [$j];
}
}
$result[]=$element;
$element='';
}
print_r($result);
This implementation returns all the combinations of all items (77 = 823542 combinations of 7 items):
function combine_all(array $numbers) {
$count = count($numbers);
$result = array_map('strval', $numbers);
for($i = 1; $i < $count; ++$i) {
$combinations = array_slice($result, pow($count, $i-1));
foreach($numbers as $number) {
foreach($combinations as $combination) {
$result[] = $number . ',' . $combination;
}
}
}
return $result;
}
When using print_r to output the data, it can perform very slowly:
$array = array_fill(0, pow(7,7), '');
$t = microtime(true);
echo '<pre>';
print_r($array);
echo '</pre>';
echo microtime(true) - $t;
// 0.75329303741455
$t = microtime(true);
echo '<pre>';
print_r( combine_all(array(1,2,3,4,5,6,7)) );
echo '</pre>';
echo microtime(true) - $t;
// 1.7037351131439
$t = microtime(true);
combine_all(array(1,2,3,4,5,6,7));
echo microtime(true) - $t;
//0.75869607925415
To restrict the items number, use the array_slice function:
combine_all(array_slice($numbers, 0, 7));
If you really want a recursive function, you could do something like this:
function combine_all(array $numbers, $cnt=null, $baseCombination=null) {
if( $baseCombination === null ) {
$cnt = count($numbers);
}
if( $cnt > 0 ) {
$result = array();
foreach($numbers as $number) {
$combination = $number . ',' . $baseCombination;
$result[] = $combination;
$result = array_merge($result, combine_all($numbers, $cnt-1, $combination));
}
return $result;
}
return array();
}
But it takes too much memory.
I finally found out a way to add recursive function to create unique combinations from given numbers:
$numbers = [1, 2, 3, 4, 5, 6, 7];
function subsetSumRecursive($numbers, $arraySize, $level = 1, $i = 0, $addThis = [])
{
// If this is the last layer, use a different method to pass the number.
if ($level == $arraySize) {
$result = [];
for (; $i < count($numbers); $i++) {
$result[] = array_merge($addThis, array($numbers[$i]));
}
return $result;
}
$result = [];
$nextLevel = $level + 1;
for (; $i < count($numbers); $i++) {
// Add the data given from upper level to current iterated number and pass
// the new data to a deeper level.
$newAdd = array_merge($addThis, array($numbers[$i]));
$temp = subsetSumRecursive($numbers, $arraySize, $nextLevel, $i, $newAdd);
$result = array_merge($result, $temp);
}
return $result;
}
echo "<pre>";
print_r(subsetSumRecursive($numbers, 7));
echo "</pre>";

push array into an array in php

I have this snippet where I am trying to generate array of array of array of random numbers.
function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
$points = array();
$score = array();
$res = array();
$val = array();
for ($i = 0; $i <= $pACount; $i++) {
for ($j = 0; $j <= $pBCount; $i++) {
for ($k = 0; $k <= $pCCount; $i++) {
for ($l = 0; $l <= $pDCount; $i++) {
$points[] = rand(5, 95);
}
$score[] = $points;
}
$res[] = $score;
}
$val[] = $res;
}
return $val;
}
When I return this to AJAX it is returned as: [[[[5, 32, 73, 62, 45]]]]
which was suppose to be
[[[[5, 32, 73, 62, 45], [15, 2, 7, 6, 50]],[[25, 52, 93, 2, 5], [16, 32, 67, 63, 15]]]]
I am reletively very new to php coding(started a week back) and I have no clue here.
What am I missing?
You are using $i++ in every for loop, while it was supposed to be $j++, $k++ and $l++.
The corrected code
function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
$points = array();
$score = array();
$res = array();
$val = array();
for ($i = 0; $i <= $pACount; $i++) {
for ($j = 0; $j <= $pBCount; $j++) {
for ($k = 0; $k <= $pCCount; $k++) {
for ($l = 0; $l <= $pDCount; $l++) {
$points[] = rand(5, 95);
}
$score[] = $points;
}
$res[] = $score;
}
$val[] = $res;
}
return $val;
}

Categories