doubt in foreach -php - php

i have this code. Basically identifies if any position of array is empty or have an input equal a zero.
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $field) {
if(empty($form[$field]) || $form[$field] === 0) {
echo 'empty';
return false;
break;
}
}
}
My doubt now, is , how i can do an echo for example to show the second position is empty?
with an if? if ($form[$field][second]) ? i don't know if this is correct, or exists a better option
thanks

if $field is what you want to echo then just prepend it to 'is empty':
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $field)
{
if(empty($form[$field]))
{
echo $field.' is empty';
return false;
}
}
}
if you need the index value:
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
{
echo $k.' is empty';
return false;
}
}
}
eventually if the aim is retrieve the empty position (if check returns -1 then there are no empty positions):
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
return $k;
}
return -1;
}

Can't you do something like the following:
if (empty($form[$field+1])) {
echo 'Empty';
}

Use a recursive function like this:
function isEmpty($array){
if(is_array($array)){
foreach($array as $key=>$value){
if(isEmpty($value) !== false) return $key;
}
return false;
}else{
if($array === 0 || empty($array)){
return true;
}
}
}
This will traverse the array as deep as it goes, and return the index where it found an empty position, or false if it did not find an empty position.

Maybe I'm in totally wrongness, but why not :
if(empty($form[2]) || $form[2] === 0) {
echo 'second element is empty';
}
If your question is 'How can I know at what index am I while doing a foreach', then the answer is that :
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $i => $field) {
if ( (empty($form[$field]) || $form[$field] === 0) && ($i == 2)) {
echo '2n element is empty';
return false; // no need to break; as you have returned something.
}
}
}

Related

How to check given value present in nested array in PHP?

I am very new to the PHP, i want to check the value is present inside the associative array,please help me to acheive this thing.
public $array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
foreach($array as $key=>$condition){
if(in_array('myFunction',$array)){
//My logic
}
}
if you know the keys:
if($array['value.details']['type'] === 'myFunction') { }
if you walk through your array:
foreach($array as $key=>$val) {
if(is_array($val) && in_array('myFunction', $val)) {
//
}
}
Your array is mix of string and array, you might also wanna check the array inside your array.
$array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
$query = 'myFunction';
$isPresent = false;
foreach ($array as $data) {
if (gettype($data) === "array") {
foreach ($data as $val) {
if ($val === $query) {
$isPresent = true;
continue;
}
}
} else {
if ($query === $data) {
$isPresent = true;
continue;
}
}
}

Alternative to array_column function used as search

Search all navigation items:
$navitems_locations_array = array_unique(array_column($projects, 'location'));
asort($navitems_locations_array);
This works on my localhost but not on live. My server doesn't support it. And I'm using lower version of PHP.
And this is the error:
Fatal error: Call to undefined function array_column()
Any alternative with the same output?
Here is my sample arrray list:
Array( [ name ] => P1 [ description ] => Lorem Ipsum [ location ] => air city[ type ] => high rise[ status ] => new [ tags ] => [ page_url ] => project-1[ image ] => projects/images/p1/project-image.jpg[ timeline ] => )
Try this hope it will help you out. Here we are using array_map for gathering locations.
$locations=array();
array_map(function($value) use (&$locations) {
$locations[]=$value["location"];//we are gathering index location
}, $yourArray);//add your array here in place of $yourArray.
print_r(array_unique($locations));
It is usually useful to read User Contributed Notes on the PHP Manual.
For example below the array_column article, there are several variants of implementations for versions lower than PHP 5.5. Here is the most popular one:
if(!function_exists("array_column"))
{
function array_column($array,$column_name)
{
return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
}
But it doesn't support $index_key, so you can find another one there, which does:
if (!function_exists('array_column')) {
function array_column($input, $column_key, $index_key = null) {
$arr = array_map(function($d) use ($column_key, $index_key) {
if (!isset($d[$column_key])) {
return null;
}
if ($index_key !== null) {
return array($d[$index_key] => $d[$column_key]);
}
return $d[$column_key];
}, $input);
if ($index_key !== null) {
$tmp = array();
foreach ($arr as $ar) {
$tmp[key($ar)] = current($ar);
}
$arr = $tmp;
}
return $arr;
}
}
You can find a couple more alternatives in the User Contributed Notes.
Add your own function array_column if you PHP version does not support it:
if (!function_exists('array_column')) {
function array_column($input = null, $columnKey = null, $indexKey = null)
{
$argc = func_num_args();
$params = func_get_args();
if ($argc < 2) {
trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
return null;
}
if (!is_array($params[0])) {
trigger_error(
'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
E_USER_WARNING
);
return null;
}
if (!is_int($params[1])
&& !is_float($params[1])
&& !is_string($params[1])
&& $params[1] !== null
&& !(is_object($params[1]) && method_exists($params[1], '__toString'))
) {
trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
return false;
}
if (isset($params[2])
&& !is_int($params[2])
&& !is_float($params[2])
&& !is_string($params[2])
&& !(is_object($params[2]) && method_exists($params[2], '__toString'))
) {
trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
return false;
}
$paramsInput = $params[0];
$paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
$paramsIndexKey = null;
if (isset($params[2])) {
if (is_float($params[2]) || is_int($params[2])) {
$paramsIndexKey = (int) $params[2];
} else {
$paramsIndexKey = (string) $params[2];
}
}
$resultArray = array();
foreach ($paramsInput as $row) {
$key = $value = null;
$keySet = $valueSet = false;
if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
$keySet = true;
$key = (string) $row[$paramsIndexKey];
}
if ($paramsColumnKey === null) {
$valueSet = true;
$value = $row;
} elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
$valueSet = true;
$value = $row[$paramsColumnKey];
}
if ($valueSet) {
if ($keySet) {
$resultArray[$key] = $value;
} else {
$resultArray[] = $value;
}
}
}
return $resultArray;
}
}
Reference:

PHP checking if all inputs were set doesn't function?

So I started using MVC. I don't use a framework. It's just self-practice.
So this is my register part:
protected function _instance()
{
if ($_POST != null)
{
/**
* Validating if forms are not empty
**/
if (self::validateForms())
{
echo 1;
}
else
{
new Error("One of the forums was empty..");
}
}
}
private static function validateForms()
{
$inputs = array (
'username', 'password', 'repassword',
'email', 'password_f', 'repassword_f',
'display'
);
$i = 0;
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
}
Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?
The problem is you are returning within your loop after the first test.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
should be
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
or more concisely
foreach ($inputs as $key)
{
if (!isset($_POST[$key]) || empty($_POST[$key]))
{
return false;
}
}
return true;
You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through. Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}

php: converting an array in string

I was trying to make a function con convert an array in a string value, the code is:
function makestring($array)
{
$outval = '';
foreach($array as $key=>$value)
{
if(is_array($value))
{
$outval .= makestring($value);
}
else
{
$outval .= $value;
}
}
return $outval;
}
But I get this error: Warning: Invalid argument supplied for foreach(). Can anybody please help me?
function makestring($array)
{
if(is_array( $array )) {
$outval = '';
foreach($array as $key=>$value)
{
if(is_array($value))
{
$outval .= makestring($value);
}
else
{
$outval .= $value;
}
}
return $outval;
} else {
die("Supplied argument is not an array");
}
}
OR
function makestring( array $array)
{
// you code goes here
}
Try this. You need to check passing argument is array or not before you use foreach
To prevent an error in foreach, it's better to set type to variable:
foreach((array)$someArray as $data) {
Even if $someArray is not an array, you'll not get any error.
→ Try this:
function makestring($array)
{
$outval = '';
$keys = array_keys( $array );
for( $x = 0; $x < count( $array ); $x++ )
{
if( is_array( $array[ $keys[ $x ] ] ) )
{
$outval .= makestring( $array[ $keys[ $x ] ] );
}
else
{
$outval .= $array[ $keys[ $x ] ];
}
}
return $outval;
}
Maybe the variables you use $key and $value has old data in them , normally a unset($key,$value) in the end of a foreach will cure that
$array = array(
'1',
'2',
'3',
array(
'4',
'5',
array(
'6',
'7'
)
)
);
$output = null;
if(!is_array($array)){
$array = array($array);
}
// use a reference to the $output in the callback
array_walk_recursive($array, function($array_element) use (&$output){
if(is_object($array_element) and method_exists($array_element, '__toString')){
$array_element = strval($array_element);
}
if(is_scalar($array_element)){
$output .= $array_element;
}else{
// found a non scalar... handle it! :)
}
});
echo $output;
Check this out.
array_walk_recursive((array) $array, function($val, $key) {
global $result;
$result .= $val;
});
You check via
if(is_array($value))
{
$outval .= makestring($value);
}
whether to call makestring() recursively. However, in the code that enters makestring() in the first place, you do no such check. That's ok, but then you have to check in makestring(), whether you actually got an array from the caller. That's called defensive programming.
Another option is to do the check on the calling side. That's part of Design By Contractâ„¢:
$var = i_usually_give_you_an_array_but_i_might_also_fail();
if (is_array($var)) {
echo makestring($value);
}
recursive implode() this convert multidimensional array to string
function mYimplode($array, $delimeter) {
$result='';
foreach ($array as $key) {
if (is_array($key)) {
$result .= mYimplode($key, $delimeter) . $delimeter;
} else {
$result .= $key . $delimeter;
}
}
$result = substr($result, 0, 0-strlen($delimeter));
return $result;
}

Comparing in_array values

I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.

Categories