PHP : Get key of an array that matches specific value - php

Here is how I set my Array:
$Post_Cat_Array = array();
while($row = mysql_fetch_array( $result )) {
$Post_Cat_Array[$row['type_id']] = $row['type_name'];}
in this function I need to get the type_id(key) of a specific type_name(value)
function NameToID($input){
echo array_search($input, $Post_Cat_Array);
}
and I call the function like this :
NameToID($_POST['type']);
But it's not working. It doesn't echo anything. I am sure the $_POST['type'] contains correct value.
note:value of $_POST['type'] is in arabic. same with all values of the array.

It seems that $Post_Cat_Array is out of scope. Modify your function:
function NameToID($input, $arr){
echo array_search($input, $arr);
}
and then:
NameToID($_POST['type'], $Post_Cat_Array);
From PHP Variable scope:
This script will not produce any output because the echo statement
refers to a local version of the (...) variable, and it has not been
assigned a value within this scope.

That is because your array variable is not known to your function. You can use either of the following to achieve that
<?php
$Post_Cat_Array=array();
$Post_Cat_Array["key1"]="value1";
$Post_Cat_Array["key2"]="value2";
$Post_Cat_Array["key3"]="value3";
$Post_Cat_Array["key4"]="value4";
echo NameToID("value4");
echo "<br>";
echo NameToID2("value4",$Post_Cat_Array);
function NameToID($input){
global $Post_Cat_Array;
echo array_search($input, $Post_Cat_Array);
}
function NameToID2($input,$values){
echo array_search($input, $values);
}
?>

Related

Echoing returned value from previous function

function report_test() {
$color = "blue";
$name = "John";
mobile_test($color, $name);
echo $columnid;
}
function mobile_test($color, $name) {
-snipped Insert MySQL Query-
$columnid = 5;
return $columnid;
}
Hopefully the example above portrays what I'm attempting to do. Globalising the variable columnid isn't an option in this scenario due to other various reasons. I also do not want to alter the mobile_test($color, $name) function. I find that if I echo the function instead the MySQL Insert Query is ran twice, meaning two sets of the same results gets entered into the database.
Is there another way to do this?
I assume that you want to echo out the return value from mobile_test() inside of report_test(). The easiest way to do this is to simply echo out $columnid inisde of mobile_test(). When you call mobile_test() from report_test(), the echo statement will be called as well, and the value will be outputted:
function mobile_test($color, $name) {
...
$columnid = 5;
echo $columnid;
return $columnid;
}
There's also the possibility to make use of PHP's short tag syntax (as <?= mobile_test(); ?>), assuming you want to echo the return of the function directly, and not do anything else with it.
Note that if you leave in the return value (return $columnid;), you'll be able to use this value directly as a comparison in the report_test() function:
if (mobile_test($color, $name) === 5) {
echo "The column ID is 5" /* This line will be triggered */
}
You may do this:
function report_test() {
$color = "blue";
$name = "John";
$columnid = mobile_test($color, $name);
echo $columnid;
}
you need to store the returned value from mobile_test() as a new variable. This won't need to change the mobile_test()

Php calling functions that store values globally doesn't return desired value

For starters, I have to do it this way in my code so I'm not looking for a completely 'different' solution.
Why is this not storing/returning the value I entered to the global variables?
EDIT: I forgot to put the if inside a function so assigning 'wrong' goes globally anyway.
This is a working one.
<?php
$track;$cat;$title;
function storeData($track, $cat, $title){
$GLOBALS['track']=$track;
$GLOBALS['cat']=$cat;
$GLOBALS['title']=$title;
print 'inside function:';
print $GLOBALS['track'];
print $GLOBALS['cat'];
print $GLOBALS['title'];
return array($GLOBALS['track'],$GLOBALS['cat'],$GLOBALS['title']);
}
function getData($track, $cat, $title){
return array('track'=>$GLOBALS['track'],'cat'=>$GLOBALS['cat'],'title'=>$GLOBALS['title']);
}
$a=1;
if ($a==1) {
test($a);
}
function test($a){
$track='correct track ';
$cat='correct cat ';
$title='correct title ';
storeData($track, $cat, $title);
print 'storing this data:';
print $track;
print $cat;
print $title;
$cat='wrong'; $track='wrong'; $title='wrong';
$getting=getData();
$t=$getting['track'];
$c=$getting['cat'];
$e=$getting['title'];
print 'reading back this data:';
print $t;
print $c;
print $e;
}
?>
Output:
inside function:correct track correct cat correct title
storing this data:correct track correct cat correct title
reading back this data:correct track correct cat correct title
Your function getData() returns an array but you never used the returned value, which is what contains the correct data. And in this case you actually don't need arguments at all:
function getData()
{
return [
$GLOBALS['track'],
$GLOBALS['cat'],
$GLOBALS['title']
];
}
$data = getData();
$track = $data[0];
$cat = $data[1];
$title = $data[2];
Or use list(), for a neater assignment:
list($track, $cat, $title) = getData();
If however you want the function to assign to variables by itself, note that PHP functions are pass-by-value by default. So when you pass the arguments, you're passing a copy of their values. To pass-by-reference, you can do something like this:
function getData(&$track, &$cat, &$title)
{
$track = $GLOBALS['track'];
$cat = $GLOBALS['cat'];
$title = $GLOBALS['title'];
}
getData($track, $cat, $title);
This will modify the variables.
When you return array from the function, you should assigned back the local variables with the returned $GLOBALS values. Like this
$cat='wrong'; $track='wrong'; $title='wrong';
$returned_array = getData($track, $cat, $title);//read global var
$track = $returned_array[0];
$cat = $returned_array[1];
$title = $returned_array[2];
// then you print these variables
print 'reading back this data:';
print $track;
print $cat;
print $title;
It is because you are not saving the variables that the function getData returns.
$cat='wrong'; $track='wrong'; $title='wrong';
getData($track, $cat, $title);
print 'reading back this data:';
print $track;
print $cat;
print $title;
You are just calling the function but not saving the variables it's returning.

Check whether variable with the name of array value is set or not

So I have this array:
$myArray = array('myVar', 'myVar75', 'myVar666');
How do I isset check whether the variable called $myVar,$myVar75,$myVar666 exists or not?
What is the most sensible way of passing the array's value into the isset() function as a variable name to check?
Just use variable variables to test each element with a simple foreach loop:
Example:
$myVar666 = 1; // for example's sake
$myArray = array('myVar', 'myVar75', 'myVar666');
foreach($myArray as $element) {
if(isset(${$element})) {
echo $element, ' is already set';
} else {
echo $element, ' is not yet set';
// if not set, do something here
}
}
Should yield something like this:
$myVar is not yet set
$myVar75 is not yet set
$myVar666 is already set
foreach($myArray as $value){
if(isset($$value)){
echo "$value is exist with value : '".$$value."'";
}
else{
"$value is not exist";
}
}
You'd do that by putting an extra $, as follows:
$myArray = array("myVar", "myVar75", "myVar666");
if (isset($$myArray[0])) {
//Content
}
That would check if $myVar is set. Change the index to myArray accordingly.
The way to think about PHP's implementation of this (called variable variables) is that the content of the string goes after the dollar sign:
$hi = "hello";
But if you put $$hi, then the $hi is replaced with the string's content, so it becomes $hello.
$hi = "hello";
$hello = "greetings";
If you put $$$hi, then the $hi is replaced so that it becomes $$hello, and the $hello is replaced so that it becomes $greetings.

How do I return a single value from an array output by a function without declaring a variable first?

Let's say I have this:
function data() {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
return $out;
}
I can output the data by declaring it as a variable, then using the array index to echo it:
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
But, I'm calling functions inline with other functions, and I'm trying to avoid having to declare a variable first. For instance, I want to do something like this:
echo data()[0]; //pulls first value in array without declaring it as a variable first. This needs to be variable i.e. data()[1] data()[2] etc.
Or more specifically, I'm actually trying to do it as a class:
$traverseXML->getData("Route", "incoming", "field", "value")[0]
//getData() returns an array, I'm trying to get a single value.
Personally i would do something like this
<?php
function data($key = false, $default = 'not found') {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
if($key)
{
if(isset($out[$key]))
return $out[$key];
else
return $default;
}
else
return 'empty';
}
?>
<?= data('a') ?>

PHP Foreach array as a error in function (invalid argument for foreach in...)

Im working on a new minimal Project, but i've got an error, i dont know why.
Normally, i use arrays after i first created them with $array = array();
but in this case i create it without this code, heres an example full code, which outputs the error:
<?php $i = array('demo', 'demo'); $array['demo/demodemo'] = $i; ?>
<?php $i = array('demo', 'demo'); $array['demo/demodemo2'] = $i; ?>
<?php
foreach($array as $a)
{
echo $a[0] . '<br>';
}
function echo_array_demo() {
foreach($array as $a)
{
echo $a[0] . '<br>';
}
}
echo_array_demo();
?>
I create items for an array $array and if i call it (foreach) without an function, it works. But if i call in in a function, then the error comes up...
I ve got no idea why
Thank you...
Functions have their own variable scope. Variables defined outside the function are not automatically known to it.
You can "import" variables into a function using the global keyword.
function echo_array_demo() {
global $array;
foreach($array as $a)
{
echo $a[0] . '<br>';
}
}
Another way of making the variable known to the function is passing it as a reference:
function echo_array_demo(&$array) {
foreach($array as $a)
{
echo $a[0] . '<br>';
}
}
echo_array_demo($array);
Check out the PHP manual on variable scope.

Categories