php multidimensional array if loop - php

I have a multidimensional array like this
$array['value'][1][1]
Now i would like to implement if loop like this
if ($value = $array['value'][1][1]) {
echo "It works";
}
Now it works if i assign the values like [1][1],[2][1].
Is it possible to compare the whole array.
I mean if the array looks like
array[value][1][1],array[value][2][1],..........,array[value][n][1]
It works should be echoed.
I tried like this.
if ($value = $array['value'][][]) {
echo "It works";
}
But its not working. Can anyone give me the correct syntax?

I'm not sure if this is what you're looking for but you could try this function
$value is 1 in your case
function($array,$value)
foreach($array['amazon'] as $val){
if($value != $val[1])return FALSE;
}
return TRUE;
}
The function runs through $array['amazon'][*] and checks condition for each value. If found FALSE for any it returns

Based on your comments of what you're trying to accomplish, I think the following may solve your dilemma. Let me know if I'm going the wrong direction with this or have any additional questions/concerns.
<?php
$forms = array(
'amazon' => array(
0 => array(
1 => 111,
),
1 => array(
1 => 222,
),
2 => array(
1 => 333
)
)
);
$value = 333;
$it_works = False;
foreach($forms['amazon'] as $array) {
if($array[1] == $value) {
$it_works = True;
break;
}
}
if($it_works === True) {
print 'It Works!';
}
?>

You can try this:
$itWorks = true;
for( $a = 0; $a < sizeof( $array[value] ); $a ++ ){
if ( $value != $array[value][$a][1] ){
$itWorks = false;
break;
}
}
if( $itWorks ){
echo "It works";
}
Of course you must replace [value] with a legitimate value

function check() {
for($i = 0; $i < count($array[$value]); $i++) {
if($value != $array[$value][$i][1])
return FALSE;
}
echo 'It works!';
}

Related

check if string exists in array element

Is there any function that can do what strpos does, but on the elements of an array ? for example I have this array :
Array
(
[0] => a66,b30
[1] => b30
)
each element of the array can contain a set of strings, separated by commas.
Let's say i'm looking for b30.
I want that function to browse the array and return 0 and 1. can you help please ? the function has to do the oppsite of what this function does.
Try this (not tested) :
function arraySearch($array, $search) {
if(!is_array($array)) {
return 0;
}
if(is_array($search) || is_object($search)) {
return 0;
}
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) {
continue;
}
if(strpos($v, $search) !== false) {
return 1;
}
}
return 0;
}
You could also use preg_grep for this.
<?php
$a = array(
'j98',
'a66,b30',
'b30',
'something',
'a40'
);
print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );
https://eval.in/412598

Recursive PHP Function

I am trying to solve this problem to learn logic formulations, but this one's really taken too much of my time already.
Rules are simple, No loops and no built in PHP functions (eg. print_r, is_array.. etc).
This is what I have come up with so far.
function displayArray(array $inputArray, $ctr = 0, $tempArray = array()) {
//check if array is equal to temparray
if($inputArray != $tempArray) {
// check if key is not empty and checks if they are not equal
if($inputArray[$ctr]) {
// set current $tempArray key equal to $inputArray's corresponding key
$tempArray[$ctr] = $inputArray[$ctr];
if($tempArray[$ctr] == $inputArray[$ctr]) {
echo $tempArray[$ctr];]
}
$ctr++;
displayArray($inputArray, $ctr);
}
}
}
This program outputs this:
blackgreen
The problem starts when it reaches the element that is an array
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
displayArray($array);
Any tips?
This what the return value is supposed to be: blackgreenpurpleorange
This was fun. I decided to make it work with most data types while I was at it. Just don't throw it any objects or nulls and things should work.
No more # error suppression. Now returns the string instead of echoing it.
I realized too late that isset() is actually a language construct rather than a function, and went with a null termination strategy to determine the end of the arrays.
function concatinateRecursive($array, $i = 0) {
static $s = '';
static $depth = 0;
if ($i == 0) $depth++;
// We reached the end of this array.
if ($array === NULL) {
$depth--;
return true;
}
if ($array === array()) return false; // empty array
if ($array === '') return false; // empty string
if (
$array === (int)$array || // int
$array === (float)$array || // float
$array === true || // true
$array === false || // false
$array === "0" || // "0"
$array == "1" || // "1" "1.0" etc.
(float)$array > 1 || // > "1.0"
(int)$array !== 1 // string
)
{
$s .= "$array";
return false;
}
// Else we've got an array. Or at least something we can treat like one. I hope.
$array[] = NULL; // null terminate the array.
if (!concatinateRecursive($array[$i], 0, $s)) {
$depth--;
return concatinateRecursive($array, ++$i, $s);
}
if ($depth == 1) {
return $s;
}
}
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
echo concatinateRecursive($array);
blackgreenpurpleorange
Live demo
What about this? You must check if it is array or not.
function display_array(&$array, $index=0) {
if (count($array)<=$index) return;
if (is_array($array[$index])) {
echo '[ ';
display_array($array[$index]);
echo '] ';
}
else
echo "'" . $array[$index] . "' ";
display_array($array, $index+1);
}
// Try:
// $a = ['black', 'green', ['purple', 'orange'], 'beer', ['purple', ['purple', 'orange']]];
// display_array($a);
// Output:
// 'black' 'green' [ 'purple' 'orange' ] 'beer' [ 'purple' [ 'purple' 'orange' ] ]
try this have to use some inbuilt function like isset and is_array but its a complete working recursive method without using loop.
function displayArray(array $inputArray, $ctr = 0) {
if(isset($inputArray[$ctr]))
{
if(is_array($inputArray[$ctr]))
{
return displayArray($inputArray[$ctr]);
}
else
{
echo $inputArray[$ctr];
}
}
else
{
return;
}
$ctr++;
displayArray($inputArray, $ctr);
}
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
displayArray($array);
OUTPUT :
blackgreenpurpleorange
DEMO
complete answer
$myarray = array(
'black',
'green',
array(
'purple',
'orange'
)
);
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $k => $value) {
if($k<10){
//printAll($k);
printAll($value);
}
}
}
printAll($myarray);

how to find which if statement is met

I have the following if statement
if ( $missCh[0]['type']==4 OR $missCh[1]['type'] == 4 OR $missCh[2]['type'] == 4 ) {
echo 'go ahead';
}
I would like to find out if $missCh[0] or [1] or [2] is meeting the statement so that I can then ask if($missCh[X]['value]==3) but I don't know which part of the array holds true.
$types = array( $missCh[0]['type'], $missCh[1]['type'], $missCh[2]['type'] );
foreach ( $types as $key => $val ) {
if ( $val == 4 ) $fours[] = $key;
}
foreach ( $types as $key => $val ) {
if ( in_array( $key, $fours ) ) continue;
if ( $val == 3 ) $threes[] = $key;
}
print_r( $fours );
print_r( $threes );
I would like to find out if $missCh[0] or [1] or [2] is meeting the statement
AS you currently have it, you're not going to be able to manage this within the script as you currently allow the echo to be actioned if ANY of the criteria return TRUE.
If you want to action something based on what a particular array value is individually, you'll need to check each individually and action as appropriate:
if($missCh[0]['type']==4)
{
//Do something
}
elseif ($missCh[1]['type']==4)
{
//Do something
}
elseif($missCh[2]['type']==4)
{
//Do something
}
If appropriate, your final elseif could be just else, which would then be a catch all if none of the previous checks returned TRUE.
I've isolated the responsibility to check the if in a function. That function echoes "go ahead" and return the index $miss[$i]['type'] which is equals to 4.
<?php
$miss[0]['type'] = 2;
$miss[1]['type'] = 4;
$miss[2]['type'] = 5;
function goAhead($miss) {
for($i=0;$i<=count($miss);$i++) {
if($miss[$i]['type']==4) {
echo 'go ahead';
return $i;
}
}
}
$i = goAhead($miss);
echo $i;
This solution will work with one or infinite indexes or $miss array. This means that you will never need to refactor this code if $miss array will growth.

How to check an empty slot in 3 dimensional array in PHP?

I have coding about 3 dimensional array. I need a function to automatically check where the empty slot is, and then insert the empty array ($rhw[104][1][2]) values Class C.
The coding structure is,
$rhw[101][1][2] = "Class A";
$rhw[102][1][2] = "Class B";
$rhw[103][1][2] = "";
And i just can make like the coding below,
if (empty($rhw[103][1][2])) {
echo "TRUE";
} else {
echo "FALSE";
}
But there is already declared like --- if (empty($rhw[103][1][2])) ---
I dont know how to automatically check where the empty slot is (which is $rhw[103][1][2]).
Such as,
if (empty($rhw[][][])) {
insert "Class C";
} else {
echo "The slot has been fulfilled";
}
But it can not be proceed.
Thank you, guys! :)
Taken from in_array() and multidimensional array
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
For check a particular position, you can use a more simple solution:
if(isset($rhw[103]) && isset($rhw[103][1]) && isset($rhw[103][1][2]))
{
echo "TRUE";
}
else
{
echo "FALSE";
}
Or use a function for check isset for each multidimensional position.
function check_multidimensional($data, $a, $b, $c)
{
return isset($data[a]) && isset($data[$a][$b]) && isset($data[$a][$b][$c]);
}
You can even make a more generic function for N dimensions.
Coba ini deh udah di edit. penasaran :p
$rwh = array(
101 => array( 1 => array(1 => 'Value key 1', 2 => 'Class A')),
102 => array( 1 => array(1 => 'Value key 1', 2 => 'Class B')),
103 => array( 1 => array(1 => 'Value key 1', 2 => ''))
);
echo 'PERTAMA : '.print_r($rwh);
function emptyArray($array = array() , $newval = '')
{
$key_val = array();
if(is_array($array) && !empty($array))
{
foreach($array as $key => $value)
{
$key_val[$key] = emptyArray($value, $newval);
}
}
else if(empty($array))
return $newval;
else
return $array;
return $key_val;
}
$hasil = emptyArray($rwh, 'Class C');
echo "AKHIR : ". print_r($hasil);

How to check if a certain part of the array exists in another array?

I have an two associative arrayes and I want to check if
$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]
The values doesn't matter, just the "path".
Does array_ intersect_ assoc do what I need?
If not how can I write one myself?
Try this:
<?php
function array_path_exists(&$array, $path, $separator = '/')
{
$a =& $array;
$paths = explode($separator, $path);
$i = 0;
foreach ($paths as $p) {
if (isset($a[$p])) {
if ($i == count($paths) - 1) {
return TRUE;
}
elseif(is_array($a[$p])) {
$a =& $a[$p];
}
else {
return FALSE;
}
}
else {
return FALSE;
}
$i++;
}
}
// Test
$test = array(
'foo' => array(
'bar' => array(
'baz' => 1
)
),
'bar' => 1
);
echo array_path_exists($test, 'foo/bar/baz');
?>
If you only need to check if the keys exist you could use a simple if statement.
<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]
)) {
//exists
}

Categories