Kshitij Yelpale February 2016

How to add key to label when label has value exactly same to key ? ....PHP

User gives a input for label and for key too with the other parameters(Key and Label are just example) I want to add Key to label only once means only at first execution (first button press - but after that on every button click it should not add; php file loads on every button)after that it should be avoided to add (prepend) (key_valuelabel_value) So my existing code adds key to label but this fails when if user gives label which has value similar to key.

For example:- key='123' and label='123 test' then my condition fails.

So anyone suggest me on this how can I handle this case ?

This is php, everytime it reloads so counter also failed.

Answers


Wizard February 2016

I don't asking why do you need that. Hope this code can helps:

function isKeyInLabel($key, $label) {
    $keys = explode(' ', $label);

    // remove last element (it's a label)
    array_pop($keys);

    return in_array($key, $keys);
 }

usage example:

 // this condition will returns true
 if (isKeyInLabel('456', '123 456 789 test')) {
    // already exists
 }

notice: of course you can't use keys or labels with spaces

UPD: You'll need another variable, for example:

// of course you need a place where you can save this array
// as possible place you can use session or cookies, or
// whatever you want, here is session usage example
session_start();

// this hash will have keys that already executed
$execKeys = isset($_SESSION['execKeys'])?$_SESSION['execKeys']:array();

// assuming that $execKeys[$label] is an array
if (isset($execKeys[$label]) && in_array($key, $execKeys[$label])) {
  // code already executed
} else {
    $execKeys[$label] = isset($execKeys[$label])?$execKeys[$label]:array();
    $execKeys[$label][] = $key;
    // and if you still need it
    $label = $key.' '.$label;
}

$_SESSION['execKeys'] = $execKeys;

Post Status

Asked in February 2016
Viewed 2,495 times
Voted 12
Answered 1 times

Search




Leave an answer