How to check if specific value exists in side an array? - php

I have the following sample function.
class EquipmentReport extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Reporting/ReportModel');//load report model
$this->load->helper('url');
$this->load->helper('form');
$this->Authorize(); // method inherited and returns array
}
/**
* loads view if no $_POST data
* if post data generates sql query
* #return (query)
**/
public function by_category (){
$my_array = $this->Authorize();
if (in_array("USER_GROUP_STATUS", $my_array)) {
echo "Got USER_GROUP_STATUS";
}
}
dumping $my_array gives the following array
Array (
[0] => 'ALL',
'USER_GROUP_STATUS',
'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART'
)
but checking array keys is nt working.
what I wanted to do is to check if the one of the values exist. for example if 'USER_GROUP_STATUS' exists in the array ?

Try this in_array() function
if (in_array("USER_GROUP_STATUS", $your_array)) {
echo "Got USER_GROUP_STATUS";
}
or You can try this way
$ary = [
0 => ['ALL', 'USER_GROUP_STATUS', 'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART']
];
foreach($ary as $ar)
if (in_array("USER_GROUP_STATUS", $ar)) {
echo "Got USER_GROUP_STATUS";
}
Live Demo

Simply use in_array() :
if (in_array($string, $Arr)) {
//code
}

$yourArray = Array ( [0] => ALL,'USER_GROUP_STATUS','USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT','USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT','USER_GROUP_HAS_PERMISSION_UPDATE_DEPART' );
$needle = 'USER_GROUP_STATUS';
if(in_array($needle, $yourArray)) {
echo 'found it!';
}
Hope this helps you.

do sth like this
public function by_category()
{
$key= "USER_GROUP_STATUS";
$my_array = $this->Authorize();
if(in_array($key,$my_array)) {
echo 'Bravo!';
die();
}
}

Related

Arrays in php oop

I have array, where i put data depend on the url. But there is the problem, i can not print this array like in the simple php:
$array = ["hi", "name"]; echo $array[1];
what is wrong in my code that i will show, and how i can print the array
Code:
<?php
class Translate {
public $transl = [];
public function getTransl($transl = []) {
if (( isset($_GET['lang']))) {
if ($_GET['lang'] == "en") {
$this->transl = ['word1', 'word2'];
}
if ($_GET['lang'] == "ru") {
$this->transl = ['word3', 'word4'];
}
}
}
}
$test = new Translate();
$test->getTransl([0]);
?>
No idea, why are you using $transl = [] in method parameter when you need specific index, here you can just pass key which you need.
Example:
<?
class Translate {
public $transl = 0;
public function getTransl($transl = '') {
if (( isset($_GET['lang']))) {
if ($_GET['lang'] == "en") {
$this->transl = ['word1', 'word2'];
}
if ($_GET['lang'] == "ru") {
$this->transl = ['word3', 'word4'];
}
}
return $this->transl[$transl];
}
}
$test = new Translate();
echo $test->getTransl(0); // this will print `word1` if $_GET['lang'] equal to `en`
?>
In your code, you are not using either echo or return in your method to get the result, and you are not matching $transl with $this->transl anywhere to get the specific index.
First, you don't pass the index as a parameter. You use it as an index. Proper syntax would be:
$test->getTransl()[0];
That assumes that $test->getTransl() returns an array. But it doesn't. It doesn't return anything. It just sets the class attribute $transl. So, you have to do it in two lines:
$test->getTransl(); // This sets the attribute
$test->transl[0]; // This uses the attribute
But, that goes against that the method implies. The method implies that it returns the transl attribute. So, you SHOULD return it in the function with:
return this->transl;
Then, you can use:
$test->getTransl()[0];
Of course, this won't print anything. You need to precede with with echo or print:
echo $test->getTransl()[0];
I think you'll just need to return the output.
Let's say you have a file named test.php on your server
class Translate {
public $transl = [];
public function getTransl($transl = []) {
if (( isset($_GET['lang']))) {
if ($_GET['lang'] == "en") {
$this->transl = ['word1', 'word2'];
}
if ($_GET['lang'] == "ru") {
$this->transl = ['word3', 'word4'];
}
}
return $this->transl;
}
}
$test = new Translate();
$output=$test->getTransl([0]);
echo "<pre>";
print_r($output);
echo "</pre>";
Running http://server/{{enterfolderhere}}/test.php?lang=en in your browser will give
Array
(
[0] => word1
[1] => word2
)
Running http://server/{{enterfolderhere}}/test.php?lang=ru in your browser will give
Array
(
[0] => word3
[1] => word4
)
There are a few issues with your code as others have pointed out. But from a code structure point of view, there are some more fundamental issues (IMHO).
If you are going to create a translator, basing it on if $_GET variables means it can be difficult to test. In this example, you send in a language you want in the constructor and then the class will just set the private translator variables to the table of translations.
Secondly - using numeric values for the word your after can be prone to errors (so can this method, but less so). In this case, the key of the translation is the word you want to start with and the value is the new word, so rather than
echo $test->getTransl(0);
you use
echo $russianTrans->getTransl("word2");
This is the code, hope it helps...
class Translate {
// Use private variables whenever possible
private $transl = [];
public function __construct( string $lang ) {
if ($lang == "en") {
$this->transl = ['word1' => 'word1', 'word2' => 'word2'];
}
if ($lang == "ru") {
$this->transl = ['word1' => 'word3', 'word2' => 'word4'];
}
}
public function getTransl($word) {
return $this->transl[$word];
}
}
$russianTrans = new Translate($_GET['lang']); // Or hardcode it to 'ru' for example
echo $russianTrans->getTransl("word2");

how to pass a value from a recursive function into an array in a different method

I'm struggling to pass a value from a recursive function into an array in a different method. I have written my recursive function below.
function get_parent_basket_id($parent_id) {
if($parent_id==NULL){
return false;
}
$baskets = $this->Model_cds_clients->clients($parent_id)->result();
if(count($baskets)==0){
return false;
}
foreach ($baskets as $row) {
if($row->parent_id==0){
return $row->id;
} else {
$this->get_parent_basket_id($row->parent_id);
}
}
}
My Model_cds_clients code is below
function clients ($parent_id) {
$this->db->select('endpoint, parent_id');
$this->db->from('cds_clients');
$this->db->where('parent_id', $parent_id);
$this->db->where('active', 1);
$result = $this->db->get();
return $result;
}
My table structure for my model looks like below
id - int(11)
name - varchar(255)
endpoint - varchar(64)
active - tinyint(1)
parent_id - int(11)
Below is my function where I need to pass the variable into the client_id under the endpoints array.
public function __construct() {
parent::__construct();
$this->load->model('Model_story');
$this->get_parent_basket_id($parent_id);
$data = array(
'basket_id' => $this->basketId,
'story_id' => $this->storyId,
'payload' => $this->xmlString,
'endpoints' => array(
array(
'client_id' => XXXX,
'endpoint_url' => 'http://www.example.com/consume.php'
), )
);
$json_payload = json_encode($data);
Please help.
I'm not sure if this is what you are looking for, but it's what sticks out to me
Change:
foreach ($baskets as $row) {
if($row->parent_id==0){
return $row->id;
} else {
$this->get_parent_basket_id($row->parent_id);
}
}
to:
foreach ($baskets as $row) {
if($row->parent_id==0){
return $row->id;
} else {
return $this->get_parent_basket_id($row->parent_id);
}
}
in your recursive function. This way the id will actually get passed back.
Then, in your controller, assign the result to a variable i.e.
$parent_basket_id = $this->get_parent_basket_id($parent_id);
However, it doesn't look like you're declaring/passing $parent_id to __construct() so I'm not sure how this is meant to work.
Hope this help!
Your tail recursion's base case doesn't look quite right. Your direct call needs to return the results. I have re-factored your method as follows:
function get_parent_basket_id($parent_id) {
if(!$parent_id){
return false;
}
// Your method chaining is missing brackets on $this->Model_cds_clients()
$baskets = $this->Model_cds_clients()->clients($parent_id)->result();
if(!count($baskets)){
return false;
}
foreach ($baskets as $row) {
if(!$row->parent_id){
return $row->id;
} else {
// Add a return here
return $this->get_parent_basket_id($row->parent_id);
}
}
}
I hope the preceding code helps you. :)

Maintain Element in PHP Array And Update in PHP Class

I have one PHP class as below (part of the code):
class myclass{
private static $arrX = array();
private function is_val_exists($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->is_val_exists($needle, $element))
return true;
}
return false;
}
//the $anInput is a string e.g. Michael,18
public function doProcess($anInput){
$det = explode(",", $anInput);
if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
//update age of Michael
}
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
The calling code in index.php
$msg = 'Michael,18';
myclass::getHandle()->doProcess($msg);
In my webpage says index.php, it calls function doProcess() over and over again. When the function is called, string is passed and stored in an array. In the next call, if let's say same name is passed again, I want to update his age. My problem is I don't know how to check if the array $arrX contains the name. From my own finding, the array seems to be re-initiated (back to zero element) when the code is called. My code never does the update and always go to the array_push part. Hope somebody can give some thoughts on this. Thank you.
There is a ) missing in your else condition of your doProcess() function, it should read:
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
)); // <-- there was the missing )
}
Here is a complete running solution based on your code:
<?php
class myclass{
private static $arrX = array();
private function is_val_exists($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->is_val_exists($needle, $element))
return true;
}
return false;
}
//the $anInput is a string e.g. Michael,18
public function doProcess($anInput){
$det = explode(",", $anInput);
if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
//update age of Michael
for ($i=0; $i<count(self::$arrX); $i++) {
if (is_array(self::$arrX[$i]) && self::$arrX[$i]['name'] == $det[0]) {
self::$arrX[$i]['age'] = $det[1];
break;
}
}
} else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
$mc = new myclass();
$mc->doProcess('Michael,18');
$mc->doProcess('John,23');
$mc->doProcess('Michael,19');
$mc->doProcess('John,25');
print_r($mc->returnProcess());
?>
You can test it here: PHP Runnable
As I said in comments, it looks like you want to maintain state between requests. You can't use pure PHP to do that, you should use an external storage solution instead. If it's available, try Redis, it has what you need and is quite simple to use. Or, if you're familiar with SQL, you could go with MySQL for example.
On a side note, you should read more about how PHP arrays work.
Instead of array_push, you could have just used self::$arrX[] = ...
Instead of that, you could have used an associative array, e.g. self::$arrX[$det[0]] = $det[1];, that would make lookup much easier (array_key_exists etc.)
Can you try updating the is_val_exists as follows:
private function is_val_exists($needle, $haystack) {
foreach($haystack as $element) {
if ($element['name'] == $needle) {
return true;
}
return false;
}

Call a function within a function display both within array

how do I call a function from within a function?
function tt($data,$s,$t){
$data=$data;
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
I want 'two' to be shown within the array like
$o[]='one';
$o[]='two';
print_r($o);
function tt($s, $t, array $data = array()) {
$data[] = $s;
if ($t == 0) {
$data = tt('two', 1, $data);
}
return $data;
}
print_r(tt('one', 0));
This is all that's really needed.
Put the array as the last argument and make it optional, because you don't need it on the initial call.
When calling tt recursively, you need to "catch" its return data, otherwise the recursive call simply does nothing of lasting value.
No need for the else, since you're going to append the entry to the array no matter what and don't need to write that twice.
Try this one (notice the function signature, the array is passed by ref &$data):
function tt(&$data,$s,$t){
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
$array = [];
tt($array,'one',0);
print_r($array);
/**
Array
(
[0] => one
[1] => two
)
*/
try this
function tt($data,$s,$t){
global $data;
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
OUTPUT :
Array
(
[0] => one
[1] => two
)
DEMO

Searching an array for an object's member variable

How would something like this be possible:
I have an object called Player:
class Player
{
public $name;
public $lvl;
}
and I have an array of these players in: $array.
For example $array[4]->name = 'Bob';
I want to search $array for a player named "Bob".
Without knowing the array key, how would I search $array for a Player named "Bob" so that it returns the key #? For example it should return 4.
Would array_search() work in this case? How would it be formatted?
Using array_filter will return you a new array with only the matching keys.
$playerName = 'bob';
$bobs = array_filter($players, function($player) use ($playerName) {
return $player->name === $playerName;
});
According to php docs, array_search would indeed work:
$players = array(
'Mike',
'Chris',
'Steve',
'Bob'
);
var_dump(array_search('Bob', $players)); // Outputs 3 (0-index array)
-- Edit --
Sorry, read post to quick, didn't see you had an array of objects, you could do something like:
$playersScalar = array(
'Mike',
'Chris',
'Steve',
'Bob'
);
class Player
{
public $name;
public $lvl;
}
foreach ($playersScalar as $playerScaler) {
$playerObject = new Player;
$playerObject->name = $playerScaler;
$playerObjects[] = $playerObject;
}
function getPlayerKey(array $players, $playerName)
{
foreach ($players as $key => $player) {
if ($player->name === $playerName) {
return $key;
}
}
}
var_dump(getPlayerKey($playerObjects, 'Steve'));

Categories