php for nested loop and if not working - php

I'm new to php and I try to make a simple program. to show a result for ex : if the array only contains a the $result will be "a" , if b the $result will be "b", if a & b then "ab" etc. in this case the array contains a, b, and c and for some reason when I run it only shows "c".
here's my code :
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
for ($j=0; $j<sizeof($a); $j++) {
for ($k=0; $k<sizeof($a); $k++) {
for ($l=0; $l<sizeof($a); $l++) {
if ($a[$j] == "a"){
$result="a";
}
elseif ($a[$j] == "b") {
$result="b";
}
elseif ($a[$j] == "c") {
$result="c";
}
elseif ($a[$j] == "a" and $a[$k] == "b") {
$result="ab";
}
elseif ($a[$j] == "c" and $a[$k] == "b" and $a[$l] == "a") {
$result="abc";
}
elseif ($a[$j] == "b" and $a[$k] == "c") {
$result="bc";
}
}
}
}
echo ($result);
thanks in advance

Use only one loop and three flags. Try something like this
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$hasA = false;
$hasB = false;
$hasC = false;
for ($j=0; $j<sizeof($a); $j++) {
if ($a[$j] == "a"){
$hasA = true;
}
elseif ($a[$j] == "b"){
$hasB = true;
}
elseif ($a[$j] == "c"){
$hasC = true;
}
}
if ($hasA) echo 'a';
if ($hasB) echo 'b';
if ($hasC) echo 'c';

First of all those loops aren't really necessary.
Use php switches.
switch($value){
case "a":
// Actions here
case "b":
// Actions here
}
What you are doing in those for loops is keep overriding $result with a new value.
In the end it shows the last letter it found.
Aside from the fact, what purpose this code has. Try to look for a php debugger I would recommend using Xdebug.
A debugger helps a programmer detect problems by stepping into the code line by line and showing the state of every variable.
A good tutorial and development environnement tutorial is found here

Let's take a different approach:
$array="asdasd";
$check=$arry[0];
$all_the_same=true;
for($i=1; $i<count($array); $i++){
if(array[$i] !== $check){
$all_the_same=false;
break;
}
}
What I've done is to check all letters in the array to see if they're all the same, and set $all_the_same to false if they're not. To find out if the array has the letter you want:
if($check==="a")
echo "has 'a'";
or perhaps the more civilized switch / case statement.
The problem with your code is that you run three loops over the same data. $j changes very slowly (every sizeof($a) squared to be precise) and it's the first thing you check so it's no surprise it always shows "c".

$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$result = '';
foreach($a as $value) {
if($value == 'a')
$result .= 'a';
if($value == 'b')
$result .= 'b';
if($value == 'c')
$result .= 'c';
}
echo $result;
Here is a smoother version of what you tried to do!

sort($array);
implode( array_unique( $array ) );
As #GarethL had mentioned

here is a simpler way to achieve this:
$a = array('a', 'b', 'c');
$result = '';
if(in_array('a', $a)){
$result .= 'a';
}
if(in_array('b', $a)){
$result .= 'b';
}
if(in_array('c', $a)){
$result .= 'c';
}
echo $result;

For the intention of the question, may meet this simple code
<?php
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$result = implode($a);
echo $result;

Related

code sequences with number and letter without 0,1,o & i

i need to make code sequences
Eg. Start with A5B, next code will be A5C,A5D...
Until A59 then next A6A,A6B...A99 then next BAA,BAB,BAC
the sequences is A-Z then continuous with 2-9
$x = $last; // Get Last Value From DB
$a = substr($x,0,1); // Get First String
$b = substr($x,1,1); // Get Middle String
$c = substr($x, -1); // Get Last String
if($c == 'Z'){
$x = $a.$b.'0';
}
elseif($c == '9'){
if ($b == 'Z'){
$x = $a.'0'.'A';
}
elseif($b == '9'){
$a++;
$x = $a.'A'.'A';
}
else{
$b++;
$x = $a.$b.'A';
}
}
else{
$x++;
}
its works but the problem is how to make the code sequences without using 0,1,o & i
please help
sorry for my english
If you're not worried about performance, an easy fix is to just use a do-while loop to keep iterating until $x no longer contains any of the unwanted characters:
$x = $last; // Get Last Value From DB
do {
$a = substr($x, 0, 1); // Get First String
$b = substr($x, 1, 1); // Get Middle String
$c = substr($x, -1); // Get Last String
if ($c == 'Z') {
$x = $a.$b.'0';
} elseif ($c == '9') {
if ($b == 'Z') {
$x = $a.'0'.'A';
} elseif ($b == '9') {
$a++;
$x = $a.'A'.'A';
} else {
$b++;
$x = $a.$b.'A';
}
} else {
$x++;
}
} while (preg_match('/[01OI]/', $x));

Checking a for progression in a list of variables

Let's say I want to check for simple mathematical progression. I understand I can do it like this:
if ($a<$b and $b<$c and $c<$d and $d<$e and $e<$f) { echo OK; }
Is there a way to do it in a more convenient way? Like so
if ($a..$f isprog(<)) { echo OK; }
I don 't know if I get your problem right. But propably the solution for your progression could be the SplHeap object of the SPL delivered with php.
$stack = new SplMaxHeap();
$stack->insert(1);
$stack->insert(3);
$stack->insert(2);
$stack->insert(4);
$stack->insert(5);
foreach ($stack as $value) {
echo $value . "\n";
}
// output will be: 5, 4, 3, 2, 1
I havent heard of something like this, but how about using simple function:
function checkProgress($vars){ //to make it easie i assume that vars can be given in an array
$result = true;
for ($i=0; $i<= count($vars); $i++){
if ($i>0 && $vars[$i] > $vars[$i-1]) continue;
$result = false;
}
return $result;
}
Solved it quick and dirty:
function ispositiveprogression($vars) {
$num=count($vars)-1;
while ($num) {
$result = true;
if ($vars[$num] > $vars[$num-1]) {
$num--;
}
else { $result = false; break; }
}
return $result;
}
Create an array of values, iterate over them and maintaining a flag that checks if the current element value is greater than / less than that of the next value. Unlike some of the solutions in this thread, this doesn't loop through the whole array. It stops looping when it discovers the first value that's not a progression. This will be a lot more faster if the operation involves a lot of numbers.
function checkIfProg($arr, $compare) {
$flag = true;
for ($i = 0, $c = count($arr); $i < $c; $i++) {
if ($compare == '<') {
if (isset($arr[$i + 1]) && $arr[$i] > $arr[$i + 1]) {
$flag = false;
break;
}
} elseif ($compare == '>') {
if (isset($arr[$i + 1]) && $arr[$i] < $arr[$i + 1]) {
$flag = false;
break;
}
}
}
return $flag;
}
Usage:
$a = 2;
$b = 3;
$c = 4;
$d = 5;
$e = 9;
$f = 22;
$arr = array($a, $b, $c, $d, $e, $f);
var_dump(checkIfProg($arr, '<')); // => bool(true)
If you want the array to be created dynamically, you could use some variable variable magic to achieve this:
$arr = array();
foreach (range('a','f') as $v) {
$arr[] = $$v;
}
This will create an array containing all the values of variables from $a ... $f.

Comparing (empty) arrays in PHP

I want to write a test case to make sure a function call sets an array; however, I don't find a way to compare two arrays to make sure two empty arrays are not equal.
// code to be tested (simplified)
$foo = null;
function setFoo($input) {
global $foo;
$foo = array(); // BUG!!! The correct line would be: $foo = $input;
}
// test code
// given
$input = array();
// when
setFoo($input);
// then
if ($foo !== $input) {
// this block is not executed because "array() === array()" => true
throw new Exception('you have a bug');
}
So: What is the proper way to compare two PHP arrays and make sure, they are different instances (no matter if the content is the same)?
Memory locations refers to pointers. Pointers are not available in PHP. References are not pointers.
Anyway, if you want to check if $b is in fact a reference of $a, this is the closest you can get to an actual answer:
function is_ref_to(&$a, &$b) {
if (is_object($a) && is_object($b)) {
return ($a === $b);
}
$temp_a = $a;
$temp_b = $b;
$key = uniqid('is_ref_to', true);
$b = $key;
if ($a === $key) $return = true;
else $return = false;
$a = $temp_a;
$b = $temp_b;
return $return;
}
$a = array('foo');
$b = array('foo');
$c = &$a;
$d = $a;
var_dump(is_ref_to($a, $b)); // false
var_dump(is_ref_to($b, $c)); // false
var_dump(is_ref_to($a, $c)); // true
var_dump(is_ref_to($a, $d)); // false
var_dump($a); // is still array('foo')
I hope this solves your problem.
try this function . Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}

A particular double "for" loop

$bar contains 4 (in this example, but potentially much more than 4) values I want to copy into $foo and $blah in this way:
$foo[0] = $bar[0];
$foo[1] = $bar[2];
$blah[0] = $bar[1];
$blah[1] = $bar[3];
So, the even rows of $bar will be copied into $foo[i], and the odd rows will be copied into $blah[i].
I tried with:
for($i=0; $i<2; $i++)
{
for($j=0; $j<4; $j++)
{
if($j % 2 == 0)
{
$foo[$i] = $bar[$j]; // EVEN
}
else
{
$blah[$i] = $bar[$j]; // ODD
}
}
}
However if I show the output of $foo and $blah, $foo[0] is equal to $foo[1], and $blah[0] is equal to $blah[1], while they should contain different values.
Example:
Source:
$bar[0]: 27.8
$bar[1]: Napoli-Posillipo
$bar[2]: 29
$bar[3]: Stadio San Paolo di Napoli, Napoli
(wrong) result of the loop:
$foo[0] = 29 (it should be 27.8)
$foo[1] = 29
$blah[0] = Stadio San Paolo di Napoli, Napoli (it should be Napoli-Posillipo)
$blah[1] = Stadio San Paolo di Napoli, Napoli
Any hints?
Thanks
you have made it to complex, something simple like this should work:
foreach ($bar as $k=>$v){
if($k % 2 == 0){
$foo[] = $v; // EVEN
}else{
$blah[] = $v; // ODD
}
}
what about sth like
foreach($bar as $key => $value) {
if($key % 2 == 0) {
//even
$foo[] = $value;
}
else {
// odd
$blah[] = $value;
}
}
You said it yourself:
"So, the even rows of $bar will be copied into $foo[i], and the odd rows will be copied into $blah[i]".
Cycle all $bar, and copy odd rows into $blah, even into $foo:
for ($i = 0; $i < 4; $i++)
if ($i % 2)
$blah[$i/2] = $bar[$i];
else
$foo[$i/2] = $foo[$i];
In the general case:
switch($i % N) // "N" for Napoli :-D
{
case 0: $VAR1[$i/N] = $bar[$i]; break;
case 1: $VAR2[$i/N] = $bar[$i]; break;
...
}

PHP array comparing

I want to compare two arrays in php. I don't want to do it overall, but block by block.
kind of like this
if (a[1] == b[1]){ // do something }
if (a[2] == b[2]){ // do more }
how can i do this without a whole bunch of ifs ?
thanks in advance :)
$a = array(1, 2, 3, 5);
$b = array(1, 1, 1, 1);
$c = array('something', 'something', 'and so forth');
foreach($a as $key => $value){
if($value == $b[$key]){
echo $c[$key]. '<br />';
}
}
my answer. compare 2 arrays, then rune some code. triggered by the blocks that match
for($i=0;$i<sizeof(a);$i++){
if(a[$i]==b[$i]){
//DO SOMETHING
}
}
want to compare whole array element one by one (assuming both array of same length)
foreach($a as $key => $value){
if($value == $b[$key])
{
// do something
}
else
{
break; // stop doing something and break
}
}
if want to compare some keys
$keys = array('key1', 'key2');
foreach($keys as $value){
if($a[$value] == $b[$value])
{
// true
}
else
{
// false
}
}
$a = array(1, 3 , 5 ,6 , 7);
$b = array(3, 1, 5, 6, 8 ,9);
$array_size = min(count($a), count($b));
for ($i = 0; $i < $array_size; $i++) {
if ($a[$i] == $b[$i]) { //you could/should check whether the index is present.
//some code
}
}
This only works for arrays with the same uniformly distributed numerical index.
foreach(array_intersect_assoc($a,$b) as $key => $data)){
switch($key){
case 1:
//something
break;
case 2:
//something
break;
}
}
for ($i=0; $i < count($a) && $i < count($b); ++$i) {
if ($a[$i] == $b[$i]){
// this is true
} else {
// this is false
}
}
A good ol for loop should do the trick. You can start with an array of things to do:
$arrayOfThingsToDo = array( "someFunc", "anotherFunc", "yetAnotherFunc" );
$arrayOfA = array( "one", "two", "three" );
$arrayOfB = array( "one", "not two", "three" );
function doCompare($a, $b, $f) {
$len = count($a);
for($i = 0; $i < $len; $i++) {
if($a[$i] == $b[$i]) {
$f[$i]();
}
}
}
Good luck!

Categories