Display "Not Provided" when variable is null or empty in database - php

i have a variable array that gets all what my function has retrieved.
$array = $funcs->searchCompany($bizName);
and then i used foreach to check if the value is null for varchar and 0 for int and then i replace its value to "Not Provided" so that everytime it is being called it will say "Not Provided"
foreach ($array as $var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $var['name'];
$url = $var['url'];
$tagline = $var['tagline'];
$descrip = $var['descrip'];
$bemail = $var['bemail'];
$address = $var['address'];
$city = $var['city'];
but it seems wrong because it destroys the output instead.

You can use & here to pass the value of array to change inside foreach without actually worrying about which is the current array key, which is also sometimes called as passing a variable's value by reference.
Using foreach
foreach ($array as &$value) // note the &
{
if(empty($value)) $value = 'Not Provided';
// other values remain untouched
}
Using array_map()
$array = array_map(function($value){
if(empty($value))
return 'Not Provided';
return $value;
}, $array);
But i will suggest to go with foreach.

update your function so something like
foreach ($array as &$var) {
if($var == " " || $var == 0) {
$var = "Not Provided";
}
}
$name = $array['name'];
$url = $array['url'];
$tagline = $array['tagline'];
$descrip = $array['descrip'];
$bemail = $array['bemail'];
$address = $array['address'];
$city = $array['city'];

I would try something like this . I can not write comments so I am writing it as an answer.
What I understand from your code is your array has key value relation. That is most probably why it is not working with your single dimensional array iteration.
try this instead.
foreach ($array as $var => $value) {
if($value == " " || $value == 0 || $value == null) {
$array[$var] = "Not Provided";
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
Give it a try.

Related

PHP foreach/else issue

foreach($cases['rows'] as $i => $item) {
foreach($array as $key => $val) {
if($item['status'] == $key) {
echo $val;
}
}
}
Right now this code functions, but if $item['status'] != $key it echoes nothing. I've tried to add an else statement after the if statement except it prints it tens of times.
How can I achieve this functionality? I want it to print $item['status'] if $item['status'] != $key
Help is appreciated.
Thanks.
The way I understand the question you have two arrays:
An array containing different abbreviations and their full meaning.
Another multidimensional array containing arrays which again contain status-abbreviations.
To echo the full meaning instead of the abbreviations:
$abbreviations = array('NT' => 'Not taken',
'N/A' => 'Not available');
$data = array(array('status' => 'NT'),
array('status' => 'N/A'));
foreach($data as $item) {
if(array_key_exists($item['status'], $abbreviations)) {
echo $abbreviations[$item['status']] . PHP_EOL;
} else {
echo $item['status'] . PHP_EOL;
}
}
Result:
Not taken
Not available
Try this:
$test = null;
foreach($cases['rows'] as $i => $item) {
foreach($array as $key => $val) {
if($item['status'] == $key) {
echo $val;
}
else {
$test = $val;
}
}
}
if($test != null) {
echo $test//Or whatever you want to display
}
Without more info regarding the type of data in both arrays, I would suggest you to try:
!($item['status'] == $key) deny the correct statement
$item['status'] !== $key try also checking the same type (test this also with the equal statement to see if you get the results you expect)

Searching through an Array and replacing some of its values

I have a preg_match_all that is generating an array of urls from a string. The array resembles:
$url[0] = "http://www.siteone.com";
$url[1] = "http://www.sitetwo.com";
$url[2] = "http://www.sitethree.com/example1";
$url[3] = "http://www.sitefour.com";
$url[4] = "http://www.sitethree.com/example2";
$url[5] = "http://www.sitefive";
$url[6] = "http://www.sitesix";
$url[7] = "http://www.siteseven";
$url[8] = "http://www.sitethree.com/example3";
However, I need to be able to search through the #url array to change the value when it contains "http://www.sitethree.com" and set this particular value in the array to "no value". So that once this process was applied,, it would the array would look like this:
$url[0] = "http://www.siteone.com";
$url[1] = "http://www.sitetwo.com";
$url[2] = "no value";
$url[3] = "http://www.sitefour.com";
$url[4] = "no value";
$url[5] = "http://www.sitefive";
$url[6] = "http://www.sitesix";
$url[7] = "http://www.siteseven";
$url[8] = "no value";
I have tried numerous variations of preg_match_all and if statements within loops but just couldn't get it. Any help would be greatly appreciated.
$url = array_map(function($v) {
return strpos($v, 'http://www.sitethree.com') === false ? $v : 'no value';
}, $url);
foreach ($url as &$value) {
if (strpos($value, 'http://www.sitethree.com') === 0) {
$value = 'no value';
}
}
foreach($url as $id => $link){
if(strstr($link, 'sitethree.com')){
$url[$id] = 'no value';
}
}
print_r($url);
A simple way of doing it is this:
foreach($url as $key => $value)
{
if(stristr($value, "http://www.sitethree.com"))
{
$url[$key] = "no value";
}
}

PHP if in array, do something with the value

I am trying to check if a value is in an array. If so, grab that array value and do something with it. How would this be done?
Here's an example of what I'm trying to do:
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
if (in_array('20', $the_array)) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $found);
echo $found_parts['0']; // This would echo "jueofi31"
}
This should do it:
foreach($the_array as $key => $value) {
if(preg_match("#20#", $value)) {
$found_parts = explode('->', $value);
}
echo $found_parts[0];
}
And replace "20" by any value you want.
you might be better off checking it in a foreach loop:
foreach ($the_array as $key => $value) {
if ($value == 20) {
// do something
}
if ($value == 30) {
//do something else
}
}
also you array definitition is strange, did you mean to have:
$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
using the array above the $key is the element key (buejcxut, jueofi31, etc) and $value is the value of that element (10, 20, etc).
Here's an example of how you can search the values of arrays with Regular Expressions.
<?php
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
$items = preg_grep('/20$/', $the_array);
if( isset($items[1]) ) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $items[1]);
echo $found_parts['0']; // This would echo "jueofi31"
}
You can see a demo here: http://codepad.org/XClsw0UI
if you want to define an indexed array it should be like this:
$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
then you can use in_array
if (in_array("10", $my_array)) {
echo "10 is in the array";
// do something
}

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Comparing two identical strings returns false in PHP

I'm trying to compare two strings. When I echo them, they appear to be identical, yet when I compare them with the '==' operator, it returns false. For example, when running the code below on my database. It outputs things like "APPARENTLY Apple does not equal Apple". What is the reason?
if ($this->data['list_text']) { // The user has entered into textarea
$list = nl2br($this->data['list_text']);
$list_array = explode('<br />', $list);
$ranking = 1;
$company_array = $this->CompanyList->CompanyRanking->Company->find('list', null);
// This is the comparison bit
foreach ($list_array as $key => $value) {
$companyId = null;
foreach ($company_array as $key2 => $value2) {
if ($value2 != $value) {
echo 'APPARENTLY ' . $value2 . ' does not equal ' . $value;
} else {
$companyId = $key2;
break;
}
}
$this->data['CompanyRanking'][$ranking]['ranking'] = $ranking;
$this->data['CompanyRanking'][$ranking]['company_id'] = $companyId;
$ranking++;
}
}
Try var_dump() instead of echo.
echo 'APPARENTLY '.$value2.' does not equal '.$value;
echo '<pre>Debug: ';
echo 'value='; var_dump($value);
echo 'value2='; var_dump($value2);
echo '</pre>';
It provides additional information. E.g. the actual type. And the length of strings.
Do the strings have any extra whitespace you're not seeing? Try trimming them.
Try to check the encoding of both strings compared.
Maybe it is UTF-8 compared with ISO 8859-1 with some weird characters.
I agree with Olafur. I removed trim and replaced it with a preg_replace due to the fact you are assuming $value and $value2 are companyIDs. You can make a quick modification on these if the companyID is supposed to be alphanumeric, contain hyphens, etc... This version should do it:
if ($this->data['list_text']) {
$list = nl2br($this->data['list_text']);
$list_array = explode('<br />', $list);
$ranking = 1;
$company_array = $this->CompanyList->CompanyRanking->Company->find('list',null);
foreach ($list_array as $key => $value) {
// remove any non digit characters
$value = preg_replace('/[^0-9]/i','', $value);
$companyId = null;
foreach ($company_array as $key2 => $value2) {
// remove any non digit characters
$value2 = preg_replace('/[^0-9]/i','', $value2);
if ($value2 != $value) {
echo 'values not equal';
} else {
$companyId = $key2;
break;
}
}
$this->data['CompanyRanking'][$ranking]['ranking'] = $ranking;
$this->data['CompanyRanking'][$ranking]['company_id'] = $companyId;
$ranking++;
}
}
Try trim() for any white space as well as var_dump() to see if anything else is being passed with it.

Categories