Multidimensional array in foreach - php

i want to do the foreach only if the content of myformdata[languages1][] is not empty (include zero)
I already try:
foreach((!empty($form['languages1']) as $val){
and
if (!empty($form['languages1'][])) {
foreach($form['languages1'] as $val){
//do stuff
}
i don't have any success. At the moment with the code below the loop is made when the input of myformdata[languages1][] is 0
foreach
foreach($form['languages1'] as $val){
//do stuff
}
thanks

foreach ( $form['languages1'] as $val )
{
// If the value is empty, skip to the next.
if ( empty($val) )
continue;
}
Reference: http://ca.php.net/continue

You're dealing with type coersion
You probably want something like
if(!empty($form['languages1']) && $form['languages1'] !== 0)
So that PHP will match 0 as a number, and not as false.

Related

How to delete value from mupltiple array using key in PHP

I need one help. I need to remove value from multiple array by matching the key using PHP. I am explaining my code below.
$str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);
I have two array i.e-$arr,$arrId which has some blank value. Here I need if any of array value is blank that value will delete and the same index value from the other array is also delete.e.g-suppose for $arr the 1 index value is blank and it should delete and also the the first index value i.e-2 will also delete from second array and vice-versa.please help me.
try this:
$str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);
$arr_new=array();
$arrId_new=array();
foreach ($arr as $key => $value) {
if(($value != "" && $arrId[$key] != "")){
array_push($arr_new, $value);
array_push($arrId_new, $arrId[$key]);
}
}
var_dump($arr_new);
var_dump($arrId_new);
Try:
foreach ($arr as $key => $value) {
if ( empty($value) || empty($arrId[$key]) ) {
unset($arr[$key]);
unset($arrId[$key]);
}
}
You can zip both lists together and then only keep entries where both strings are not empty:
$zipped = array_map(null, $arr, $arrId);
$filtered = array_filter($zipped, function ($tuple) {
return !empty($tuple[0]) && !empty($tuple[1]);
});
$arr = array_map(function($tuple) {return $tuple[0];}, $filtered);
$arrId = array_map(function($tuple) {return $tuple[1];}, $filtered);
Link to Fiddle

How can I run 2 loops together in PHP without duplicating values?

I'm trying to check MD5 of some data with md5 some files, both of them are stored in one dimensional arrays. Say I have 4 files in the $files array with the same number of $datas, the following code prints "NO DIFFERENCE" 12 times instead of 4 times.
foreach($files as $file) {
foreach($datas as $data) {
if(md5($data) !== md5_file($file)) {
echo "NO DIFFERENCE";
}
}
}
How do I prevent duplicating a loop?
Update:
Both arrays $datas and $files contains equal number of values but the tricky part is the values in $files array starts from key number 2 (because I removed "." and ".." from scandir result) whereas in $datas array values start from key number 0.
the following code prints "NO DIFFERENCE" 12 times instead of 4 times.
The reason for that is you have a nested loop.
For each value in the $files array, your inner foreach will run once.
So say if you have 3 values in $files and 4 values in $datas, the loop will run as follows:
First value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Second value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Third value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Try this with one loop like this :
foreach($datas as $key => $value) {
if(md5($value) !== md5_file($files[$key])) {
echo "NO DIFFERENCE";
}
}
Note: The loop work when you have same no of values for both arrays
If you want to compare md5(files) to the mfs5(datas) you can simply do this:
for ($i = 0; $i < sizeof($files); $i++){
if(md5($datas[$i]) !== md5_file($files[$i+2]))
echo "NO DIFFERENCE";
}
If you want to check if each file have one corresponding md5(datas) then you should use you double loop as you did.
First, are you sure that !== is the operator you want to use to say 'no difference' ?
If you are looking for equality, maybe you want to use ===
Second, md5(...) is time consuming, so extract the hash in a variable.
Third, if you mean equality, you can add a break in the inner loop to stop looping as soon as you find the equality.
foreach($files as $file) {
$md5File = md5_file($file); // extract in a variable
foreach($datas as $data) {
if(md5($data) === $md5File) { // === instead of !==
echo "NO DIFFERENCE";
break; // break as soon as possible
}
}
}
You could use a callback function. But then you should be clear about how exactly you will describe an algorithm of your problem.
The following sample shows how to maybe achieve it. But it assumes that the arrays are in the same order and that you don't want to cross-compare everything. Also array_udiff may not be the best approach for it.
function compare_by_md5($data, $file) {
if( md5($data) === md5_file($file)) {
echo "NO DIFFERENCE";
}
}
array_udiff($datas, $files, 'compare_by_md5');
Sample is shown here: http://codepad.org/lYOyCuXA
If you simply want to detect if there is a difference:
$dataHashes = array();
foreach($datas as $data) {
$dataHashes[md5($data)] = true;
}
$different = false;
foreach($files as $file) {
if(!isset($dataHashes[md5_file($file)])) {
$different = true;
break;
}
}
var_dump($different);
If you want to know which files are different, then:
$dataHashes = array();
foreach($datas as $data) {
$dataHashes[md5($data)] = true;
}
foreach($files as $file) {
if(!isset($dataHashes[md5_file($file)])) {
echo $file, 'is different', PHP_EOL;
}
}

PHP Get all numerical/anonymous keys in an array

I have a multidimensional array, I am interested in getting all the elements (one level deep) that don't have named keys.
i.e.
Array
{
['settings'] {...}
['something'] {...}
[0] {...} // I want this one
['something_else'] {...}
[1] {...} // And this one
}
Any ideas? Thanks for your help.
This is one way
foreach (array_keys($array) as $key) {
if(is_int($key)) {
//do something
}
}
EDIT
Depending on the size of your array it may be faster and more memory efficient to do this instead. It does however require that the keys are in order and none are missing.
for($i=0;isset($array[$i]);$i++){
//do something
}
$result = array();
foreach ($initial_array as $key => $value)
if ( ! is_string( $key ) )
$result[ $key ] = $value;
The key is 0, Shouldn't be $your_array[0]?

Search into a multidimensional array

I have imported a CSV to fill a multidimensional array. $arrCSV.
<?php
$foundOneMatchingRow = FALSE;
foreach ($arrCSV as $row) {
if (strpos($row['5'], $val) !== FALSE && strlen($row['5']) > 4) {
$foundOneMatchingRow = TRUE;
echo $row['6'];
}
}
?>
The above code outputs from the value of $val = $_GET['menu']; which is done buy the URL.
I would like to make a search if possible please based on words in $row['6'];.
There will be a search on the page which will pass the search to the URL.
Which would look something like http://example.com/search.php?val=dogs
So the code would look for ANYTHING that relates to dog in $row [6]
I hope I have been clear. Any gudiance would be more than welcome. I am testing everything now.
Thank you
if (strpos($row['6'], $val) !== FALSE) will evaluate to true if $row['6'] contains "dog" (if $val's value is "dog"). That is, will evaluate to true as well if the string in $row['6'] is "bulldog" or "whateverdogwhatever".
BTW, why do you need this condition: strlen($row['5']) > 4? (which I guess should be at least strlen($row['6']) > 4 if you search on $row['6']).
Something else: aren't you confusing strings and integers? Maybe if (strpos($row['6'], $val) !== FALSE) should be if (strpos($row[6], $val) !== FALSE)?
EDIT
I would suggest to define constants for your CSV columns, for readability.
What about for example:
define('CSV_ID', 5);
define('CSV_TEXT', 6);
//...
foreach ($arrCSV as $row) {
if (strpos($row[CSV_TEXT], $val) !== FALSE && strlen($row[CSV_ID]) > 4) {
//...
echo $row[CSV_TEXT];
}
}

Filtering an array in php, having both value- and key-related conditions

I'm trying to filter an array, in which the filter function is supposed to check for multiple conditions. For example, if element x starts with a capital letter, the filter function should return true. Except, if the element before element x satisfies certain other conditions, then element x should not stay in the array and the filter function should therefore return false.
Problem is that the callback function in array_filter only passes the element's value and not its key... doing some magic with array_search will probably work, but I was just wondering whether I'm looking in the wrong place for this specific issue?
Sounds like a case for a good old foreach loop:
foreach ($arr as $k => $v) {
// filter
if (!$valid)
unset($arr[$k]);
}
$newArray=array();
foreach($oldArray as $key=>$value){
if(stuff){
$newArray[$key]=$value;
}
}
or
foreach($array as $key=>$value){
if(stuff){
unset($array[$key]);
}
}
Did you use simple foreach?
$prev;
$first = true;
$result = array();
foreach ($array as $key => $value)
{
if ($first)
{
$first = false;
// Check first letter. If successful, add it to $result
$prev = $value;
continue; // with this we are ignoring the code below and starting next loop.
}
// check $prev's first letter. if successful, use continue; to start next loop.
// the below code will be ignored.
// check first letter... if successful, add it to $result
}

Categories