I have this function for parsing arguments:
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--([^=]+)=(.*)', $arg, $reg)) {
$_ARG[$reg[1]] = $reg[2];
} elseif (ereg('--([a-zA-Z0-0\-]*)', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
} elseif (ereg('-([a-zA-Z0-9])', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
} elseif (ereg('([a-zA-Z0-0\-]*)', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
}
}
return $_ARG;
}
After var_dump() I get something like this:
array(4) {
["xqr"]=>
string(4) "true"
["query"]=>
string(60) "Some string..."
["input"]=>
string(12) "input03.txt"
["n"]=>
string(4) "true"
}
My problem is, that I am not able to detect duplicates in parsed arguments. For example php name.php --query='Some string...' --input=input03.txt -n -n or php name.php --query='Some string...' --input=input03.txt n n. Both inputs are invalid there can be just one -n and can't be n.
Please could you help me how to handle it? Thank you
When I understand it correct you need it for argument check provided in the command line.
I would not recommend to write/invent your own function again. Use the getopt function.
It is very powerful and you can safe time!
Related
1. Extracted from my laravel controller:
..
..
$data = json_decode($response, true);
return $data;
..
..
return view('homepage')->with('homeExclusives', $homeExclusives);
Here is a sample of the returned data, just a short version, since the returned feed is very large, but this will give you an idea of the way it's structured.
array(4) {
["success"]=> bool(true)
["status"]=> int(200)
["bundle"]=> array(2) {
[0]=> array(631) {
["StreetDirPrefix"]=> string(2) "SW"
["DistanceToStreetComments"]=> NULL
}
[1]=> array(631) {
["StreetDirPrefix"]=> string(2) "NE"
["DistanceToStreetComments"]=> NULL
}
}
I need to extract "StreetDirPrefix" value from [0] and [1], but I always get an error. Can someone help?
For the data in your example you might use array_column and specify StreetDirPrefix as the column key.
$res = array_column($array["bundle"], "StreetDirPrefix");
print_r($res);
Php demo
Without knowing what error you are getting my solution would be something like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
}
}
?>
I always like to validate arrays, so if your $data variable or the $data["bundle"] subsection are not arrays then you will not get anything. Not even an error.
I have a working example here:
https://www.seeque-secure.dk/demo.php?id=PHP+how+to+loop+over+nested+JSON+Object
EDIT:
(if i understand you correct)
When you have validated your array all you have to do is repeat the inner validation like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
if (isset($tmpVal["UnparsedAddress"])) {
echo $tmpVal["UnparsedAddress"]."\n";
}
if (isset($tmpVal["SalePrice"])) {
echo $tmpVal["SalePrice"]."\n";
}
//...... ect.....
}
}
?>
I am a new developer working at a company on a website. I am using isset() to check if something is set within a variable that I know has a value, but it is always returning false. Here is the code:
$prices_with_source = $user_company->getBranchApiImplementation()->getApiClass($controller,$apiDisabled)->getProductPrices($em, $partnership, array( array('product' => $product , 'quantity' => 1) ));
$prices_with_source = is_array($prices_with_source) ? reset($prices_with_source) : $prices_with_source;
if(isset($prices_with_source['discountedPrice']) && $prices_with_source['discountedPrice'] > 0) {
$price = $prices_with_source['discountedPrice'];
}
if(isset($prices_with_source['suggestedPrice'])) {
$price = $prices_with_source['suggestedPrice'];
}
It is supposed to enter the if statements because I know that the $price_with_sources has values. I dont know why it is not working. I used var_dump to check the value of the $prices_with_sources before the if statements and this is the output:
array(1) {
[1]=> array(3) {
["discountedPrice"]=> string(4) "5.99"
["suggestedPrice"]=> string(4) "5.99"
["source"]=> int(0)
}
}
If anyone has any helpful information it would be greatly appreciated, thanks!
Accessing a two dimension array in php
updated if block:
if(isset($prices_with_source[1]['discountedPrice']) && $prices_with_source[1]['discountedPrice'] > 0) {
$price = $prices_with_source[1]['discountedPrice'];
}
if(isset($prices_with_source[1]['suggestedPrice'])) {
$price = $prices_with_source[1]['suggestedPrice'];
}
I am wanting to check if there is data present in an array of data so that I can preform a function. Would I just use in_array?
Array:
["OpenHomes"]=>
array(2) {
[0]=>
array(2) {
["Start"]=>
string(21) "/Date(1354323600000)/"
["End"]=>
string(21) "/Date(1354326300000)/"
}
Would I just do the following?
if(in_array($detail['OpenHomes']))
{
echo 'yes';
}else{
echo 'no';
}
I am wanting to check if there is anything present within OpenHomes.
try this
if(!empty($detail) && in_array('OpenHomes',$detail))
{
echo 'yes';
}else{
echo 'no';
}
you can also check by
if ($detail['OpenHomes']) {
or
if (count($detail['OpenHomes']) > 0) { ... }
Or this
if( !empty($details['openHomes']) )
{
//
}
else
{
//
}
You can also use:
count($detail['OpenHomes'])
or
sizeof($detail['OpenHomes']) // its alias, same function with different name
to get count of elements in that array, but that will count empty elements too.
I have an array similar to this:
array(2) {
[0]=>
array(2) {
["code"]=>
string(2) "en"
["name"]=>
string(7) "English"
}
[1]=>
array(2) {
["code"]=>
string(2) "bg"
["name"]=>
string(9) "Bulgarian"
}
}
How do I check if the string Bulgarian is part of the above array, or alternatively if the lang code 'en' is part of the array? It would be great if I didn't have to use foreach to loop through the entire array and compare the string with each element['code'] or element['name'].
// $type could be code or name
function check_in_array($arr, $value, $type = "code") {
return count(array_filter($arr, function($var) use ($type, $value) {
return $var[$type] === $value;
})) !== 0;
}
I know my code used foreach but it is easy to understand and use.
$language=array();
$language[0]['code']='en';
$language[0]['name']='English';
$language[1]['code']='bg';
$language[1]['name']='Bulgaria';
var_dump(my_in_array('Bulgaria', $language));
function my_in_array($search, $array) {
$in_keys = array();
foreach($array as $key => $value){
if(in_array($search, $value)){
$in_keys[]=$key;
}
}
if(count($in_keys) > 0){
return $in_keys;
}else{
return false;
}
}
You can use this function for recursive search
function in_arrayr($needle, $haystack) {
foreach ($haystack as $v) {
if ($needle == $v) return true;
elseif (is_array($v)) return in_array($needle, $v);
}
return false;
}
Or you can use json_encode on your array and search occurence of substring :)
I had a similar problem, so I made this function, it's like in_array, but it can search in array in the array recursively. I think it's correct but I didn't test in a lot of case. (sorry for my english I'm french)
function in_arrayr($needle, $haystack) {
if(is_array($haystack)){
foreach($haystack as $elem){
$a = in_arrayr($needle,$elem)||$a;
}
}
else{
$a = (($needle == $haystack)? true: false);
}
return $a;
}
i have a piece of code , i want to get the result in on line
$lang = $this->config->item('email');
echo $lang['support_email'] ; die;
when i var_dump $lang the result
array(11) {
["useragent"]=>
string(11) "CodeIgniter"
["mailpath"]=>
string(17) "/usr/bin/sendmail"
["protocol"]=>
string(4) "mail"
["smtp_host"]=>
string(9) "localhost"
["smtp_user"]=>
string(0) ""
["smtp_pass"]=>
string(0) ""
["smtp_port"]=>
string(2) "25"
["system_email"]=>
string(21) "noreply#elephanti.com"
["help_email"]=>
string(18) "help#elephanti.com"
["inquiries_email"]=>
string(23) "inquiries#elephanti.com"
["support_email"]=>
string(21) "support#elephanti.com"
}
i tried
echo $this->config->item('email')['support_email']
and
echo echo `$this->config->item('email')->support_email
please help.............
$lang = $this->config->item('email', 'support_email');
From the doc:
http://codeigniter.com/user_guide/libraries/config.html
// Retrieve a config item named site_name contained within the blog_settings array`
$site_name = $this->config->item('site_name',
'blog_settings');
You can only do echo $this->config->item('email')['support_email'] in PHP 5.4+
Otherwise the best you can do is:
$lang=$this->config->item('email');echo $lang['support_email'];exit;
Or write a custom function to do it for you.
But then ask yourself, why must you do this on one line...?
echo $this->config->item('email')['support_email']
This actually works in PHP > 5.4. In older versions, it's not possible to do it in one statement, so you'll have to store the array in a separate local variable. You can create a function that will retrieve a value like so:
<?php
function array_get( array $array, $index ) {
return isset( $array[$index] ) ? $array[$index] : false;
}
echo array_get( $this->config->item( 'email' ), 'support_email' );
But that's useless really. Any particular reason you want to do it in one line?
Try:
foreach($lang as $key=>$val)
{
if($key == "support_email")
{
echo $val;
}
}