I want to display Yes if one of the type values begins with the letter p, however I keep outputting NONO. Any help greatly appreciated...`
<?php
$pals[] = array('name' => 'jon' , 'type' => 'peach');
$pals[] = array('name' => 'gore' , 'type' => 'choc');
foreach($pals as $key => $value) {
if (substr($value['type'], 0) === "p") {
echo "Yes";
} else {
echo "NO";
}
}
Update this line :
if (substr($value['type'], 0,1) === "p") {
Try substr($value['type'],0, 1)
To make it without substr, if you want
<?php
$pals[] = array('name' => 'jon' , 'type' => 'peach');
$pals[] = array('name' => 'gore' , 'type' => 'choc');
foreach($pals as $key => $value) {
$type = trim($value["type"]);
if ($type[0] === "p") {
echo "$type : Yes\n";
} else {
echo "$type : NO";
}
}
?>
live demo : https://eval.in/754179
Related
I am trying to figue out how to check for empty values of an array with certain exceptions. Here is the array:
[name_first] => Name
[name_last] =>
[email] => blah#blah.com
[address] =>
[country] => USA
There are two empty values - name_last & address. Here is the code:
if (in_array(null, $data)) {
echo 'empty values';
}else{
echo 'ok';
}
It will return false as [address] and [name_last] values are empty. How can I ignore a particular key (let's say - [address])? Basically it is supposed to LOOK like this:
if (in_array(null, $data) **&& key_is_not('address', 'hatever')**) {
echo 'empty values';
}else{
echo 'ok';
}
try this :
$data = array('name_first' => "Name",
'name_last' => "",
'email' => "blah#blah.com",
'address' => "",
'country' => "USA");
foreach ($data as $key => $value) {
if($value=="")
echo "$key is Empty\n";
}
Update
To exclude particular keys from the check, you can do this way :
$data = array('name_first' => "",
'name_last' => "",
'email' => "blah#blah.com",
'address' => "",
'country' => "");
$array = array("name_first","country");
foreach ($data as $key => $value) {
if($value=="" and (!in_array($key, $array)))
echo "$key is Empty\n";
}
$input_array = [
'name_first' => 'Name',
'name_last' => '',
'email' => 'blah#blah.com',
'address' => '',
'country' => 'USA',
];
Filter array ignoring the specific keys, here address and name_last
$ignore_search = in_array('', array_filter($input_array, function($k){
return !in_array($k, ['address', 'name_last']);
}, ARRAY_FILTER_USE_KEY));
Here array_filter will unset the keys specified inside.
Will return boolean depending on match found or not, if you want keys, just change in_array with array_search.
This will check to see if the value is set and the length is greater than 0, not an empty string.
foreach($elements as $key => $data)
{
if(!in_array($key, ['address', 'something']))
{
if(count($data) > 0)
{
//stuff
}
}
}
You can also ignore the key by writing a custom function that will handle the keys exception, this way you are more in control if in any case you want to tweak later:
if (in_array_except(null, $data, array("address"))) {
echo 'empty values';
}else{
echo 'ok';
}
The function will be:
function in_array_except($needle, $haystack, $exception = array(), $strict = false) {
if ($strict) {
foreach($haystack as $needle_field => $item) {
if (!in_array($needle_field, $exception) && $item === $needle)
return true;
}
} else {
foreach($haystack as $needle_field => $item) {
if (!in_array($needle_field, $exception) && $item == $needle)
return true;
}
}
return false;
}
With your current data set:
[name_first] => Name
[name_last] =>
[email] => blah#blah.com
[address] =>
[country] => USA
The output with the sample snippet is:
empty values
Try with array_search() like below::
if (array_search("", $arr)) {
echo 'empty values';
} else {
echo 'ok';
}
** Update **
$array_var = array("11" => 111, "22" => 222, "33" => 333, "44" => 444, "55" => "", "66" => 666);
$new_array_var = array();
foreach ($array_var as $key => $value) {
// echo $key . "==>" . $value . "<br/>";
if (isset($value) && $value != "") {
$new_array_var[$key] = $value;
}
}
echo "<pre>";
echo "OLD : <br/>";
print_r($array_var);
echo "<br/><br/>";
echo "NEW : <br/>";
print_r($new_array_var);
echo "</pre>";
$ignore_array = array("address");
$blank_value_keys = array_keys($data,"");
if(sizeof($blank_value_keys)>0 && sizeof(array_diff($ignore_array,$blank_value_keys)>0){
echo "Empty";
}else{
echo "NOT Empty";
}
Add all the keys to be ignored in ignore array list.
array_keys will return all the keys which have blank values.
Next we are checking if size of array returned by array_keys is greater than 0 and there are more keys in $blank_value_keys than $ignore_array than if loop executes.
Note: array_diff will return all the values available in second array but not in first
I have two arrays:
Array 1:
$art_style = ['Title1','Title2','Title3'];
Array 2:
array(
'name' => array('Title1', 'Title3', 'Title2'),
'value' => array('2,0x1,0', '2,5', '15,0'
);
I need to compare Array 2 "name" with Array 1 and output the values from Array 2 in the order of Array 1.
So the output in this case would be:
2,0x1,0 - 15,0 - 2,5
Any Idea how I could achieve that?
Try something like this:
// Array1 order
foreach ($art_style as $key => $value) {
if(in_array($value,$array2['name']))
echo $array2['value'][$key];
}
// Array2 order
foreach ($array2['name'] as $key => $value) {
if(in_array($value,$art_style))
echo $array2['value'][$key];
}
Little Long Method. But, It Worked.
<?
$array1 = ['Title1','Title2','Title3'];
$array2=array(
'name' => array('Title1', 'Title3', 'Title2'),
'value' => array('2,0x1,0', '2,5', '15,0')
);
$SizeofArray2=sizeof($array2['name']);
for($i=0;$i<$SizeofArray2;$i++)
{
$Array2Value= $array2['name'][$i];
for($j=0;$j<sizeof($array1);$j++)
{
if($Array2Value==$array1[$j])
{
if($j==$i)
{
echo " ".$array2['value'][$i];
}
if($j!=$i)
{
echo " -".$array2['value'][$i];
}
}
}
}
?>
Output: 2,0x1,0 -2,5 -15,0
try this:
$art_style = array('Title1','Title2','Title3');
$array2 = array(
'name' => array('Title1', 'Title3', 'Title2'),
'value' => array('2,0x1,0', '2,5', '15,0')
);
foreach ($art_style as $style) {
foreach ($array2['name'] as $id => $name) {
if ($name == $style) {
echo $array2['value'][$id].' - ';
break;
}
}
}
<?php
static $cnt=0;
$name='victor';
$coll = array(
'dep1'=>array(
'fy'=>array('john','johnny','victor'),
'sy'=>array('david','arthur'),
'ty'=>array('sam','joe','victor')
),
'dep2'=>array(
'fy'=>array('natalie','linda','molly'),
'sy'=>array('katie','helen','sam','ravi','vipul'),
'ty'=>array('sharon','julia','maddy')
)
);
function array_find($name,$arr)
{
global $cnt;
if(!(is_array($arr)))
return false;
foreach($arr as $val)
{
if(is_array($val))
array_find($name,$val);
else
{
$val=strtolower($val);
$item=strtolower($name);
if($val==$name)
$cnt+=1;
}
}
}
array_find($name,$coll);
if($cnt==0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
Try this code, hope it will work
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
++$cnt;
}
}
array_walk_recursive($coll, 'recursive_search' , $name);
if ($cnt == 0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
DEMO
I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}
Here is my array ouput
Array
(
[1] => 1
[2] => 2
[3] =>
)
How do I know the [3] => is empty?
foreach ($array as $key => $value) {
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
My out put showing all is not empty. What is correct way to check is empty?
An other solution:
$array = array('one', 'two', '');
if(count(array_filter($array)) == count($array)) {
echo 'OK';
} else {
echo 'ERROR';
}
http://codepad.org/zF9KkqKl
It works as expected, third one is empty
http://codepad.org/yBIVBHj0
Maybe try to trim its value, just in case that third value would be just a space.
foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
You can check for an empty array by using the following:
if ( !empty(array_filter($array))) {
echo 'OK';
} else {
echo 'EMPTY ARRAY';
}
You can use array_diff() and array_diff_key():
$array = array('one', 'two', '');
$emptyKeys = array_diff_key(array_diff($array,array()),$array);
array_diff() extracts all items which are not the same (therefore leaving out the blanks), array_diff_key gives back the differences to the original array.
$array = array('A', 'B', '');
or
$array = array('A', 'B', ' ');
An other solution:
this work for me
if(in_array(null, $myArray) || in_array('', array_map('trim',$myArray))) {
echo 'Found a empty value in your array!';
}
Here is a simple solution to check an array for empty key values and return the key.
$a = array('string', '', 5);
echo array_search(null, $a);
// Echos 1
To check if array contains an empty key value. Try this.
$b = array('string','string','string','string','','string');
if (in_array(null, $b)) {
echo 'We found a empty key value in your array!';
}
im using in my project like this for check this array
im posting form data like this array('username' => 'john','surname' => 'sins');
public function checkArrayKeyExist($arr) {
foreach ($arr as $key => $value) {
if (!strlen($arr[$key])) {
return false;
}
}
return true;
}
Try this:
<?php
$data=array(
'title' => 'Test Name Four',
'first_name' => '',
'last_name' => 'M',
'field_company' => 'ABC',
'email' => '',
'client_phone_number' => '',
'address_line_1' => '',
'address_line_2' => 'Address 3',
'address_line_3' => '',
'address_line_4' => '',
'post_code' => '',
);
echo '<pre>';
print_r($data);
foreach ($data as $key => $case ) {
echo "$key => ".is_multiArrayEmpty($case)."<br>";
}
function is_multiArrayEmpty($multiarray) {
if(is_array($multiarray) and !empty($multiarray)){
$tmp = array_shift($multiarray);
if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
return false;
}
return true;
}
if(empty($multiarray)){
return true;
}
return false;
}
?>